vikas ojha
vikas ojha

Reputation: 217

Sort a NSMutableArray in objective-c?

I am working on NSMutable Array containing list of "First Name" in it.I want to sort it alphabatically.

I tried this code

NSSortDescriptor * sortFriend = [[[NSSortDescriptor alloc] initWithKey:kfirstName ascending:YES] autorelease];
NSArray * descriptors = [NSArray arrayWithObject:sortFriend];
NSArray * sorted = [Friendsarr sortedArrayUsingDescriptors:descriptors];

correct me if i am wrong.I do have an array of names also if that could be used.

Thanks


I tried the code

NSSortDescriptor * sortFriend = [[[NSSortDescriptor alloc] initWithKey:kfirstName ascending:YES  selector: @selector(caseInsensitiveCompare:)] autorelease];
NSArray * descriptors = [NSArray arrayWithObject:sortFriend];
NSArray * arrmp = [temparray sortedArrayUsingDescriptors:descriptors];

But still my result contain 2 'k' chars. one 'k' and 'K'.I want to have case insensitive result

Upvotes: 0

Views: 7342

Answers (3)

alok srivastava
alok srivastava

Reputation: 761

You can sort NSMutable array case insensitively by this code

 NSSortDescriptor *sorter=[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(caseInsensitiveCompare:)]autorelease];
                NSArray *sortdescriptor=[NSArray arrayWithObject:sorter];
                [cpy_arr_Service_Name sortUsingDescriptors:sortdescriptor];

Upvotes: 1

vikas ojha
vikas ojha

Reputation: 217

I found the solution of sorting NSMutableArrays with sample code which can be found on the site below.

http://www.icodeblog.com/2010/12/10/implementing-uitableview-sections-from-an-nsarray-of-nsdictionary-objects/

I hope it help others to as it provides indexed sorting of a grouped table view using an array as the datasource

Upvotes: 0

Rahul Vyas
Rahul Vyas

Reputation: 28740

If your NSMutableArray only contains objects of type NSString, simply do:

[myMutableArray sortUsingSelector:@selector(compare:)];

Upvotes: 1

Related Questions