Saturday, June 1, 2013

NSMutableArray sortUsingDescriptors example in Objective C (iOS).


NSMutableArray sortUsingDescriptors

Sorts the receiving array using a given array of sort descriptors.

- (void)sortUsingDescriptors:(NSArray *)sortDescriptors

Parameters
sortDescriptors
An array containing the NSSortDescriptor objects to use to sort the receiving array's contents.

Discussion of [NSMutableArray sortUsingDescriptors]
See NSSortDescriptor for additional information.

NSMutableArray sortUsingDescriptors example.
This works like a charm!

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"crimeScene.distance" ascending:YES];
[self.arrAnnotations sortUsingDescriptors:[NSArray arrayWithObject:sorter]];

Example of [NSMutableArray sortUsingDescriptors].
Suppose there are 2 keys, integers x ascending then and strings y descending, then you may write

NSSortDescriptor* dx = [[NSSortDescriptor alloc] initWithKey:@"x" ascending:YES];
NSSortDescriptor* dy = [[NSSortDescriptor alloc] initWithKey:@"y" ascending:NO selector:@selector(caseInsensitiveCompare:)];
[arr sortUsingDescriptors:[NSArray arrayWithObjects:x, y, nil]];
[dx release];
[dy release];

NSMutableArray sortUsingDescriptors example.
You can compare as case-insensitive.

NSSortDescriptor *sorter = [[[NSSortDescriptor alloc]
          initWithKey:@"w"
          ascending:YES
          selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[mGlossaryArray sortUsingDescriptors:sortDescriptors]; 

End of NSMutableArray sortUsingDescriptors example article.