Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder elements (NSString) of an NSArray alphabetically?

How to reorder elements (NSString) of an NSArray alphabetically?

like image 801
m0rtimer Avatar asked Feb 28 '11 12:02

m0rtimer


2 Answers

NSSortDescriptor is overkill to sort an array whose elements are just NSString instances.

NSArray *sortedArray = [unsortedArray sortedArrayUsingSelector: @selector(compare:)];

If, instead of a new array instantiated with its elements sorted, you want to have the elements of an NSMutableArray instance reordered, there's a method for that:

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

Use an NSSortDescriptor instance when you have a large object managing the array for you, like an NSArrayController or an NSTableView. If that's the case, and the elements are just instances of NSString, @iHS's answer would be correct.

like image 92
Huperniketes Avatar answered Oct 21 '22 23:10

Huperniketes


you can use sortDescriptor

 NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"yourKey" ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
NSArray * sortedArray =
    [yourArray sortedArrayUsingDescriptors:descriptor];
like image 4
Ishu Avatar answered Oct 22 '22 00:10

Ishu