Archive

Archive for April, 2012

How to sort NSArray of custom objects by multiple properties – case insensitive

April 6th, 2012 No comments

Although sorting in XCode may look as something difficult, there are some quick solutions which allow us to sort array of object in less than 3 lines:

Let’s imagine that we have an array of objects. Each object has two properties: name and code. We want to sort our array by first criteria and then the other one.

We need to define sort descriptors which indicate object property to be sorted by and apply this sortDescriptors to a method sortedArrayUsingDescriptors of our NSMutableArray.

NSSortDescriptor *codeDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"code" ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
NSSortDescriptor *nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];

NSArray *sortDescriptors = [NSArray arrayWithObjects:codeDescriptor,nameDescriptor,nil];

shareClasses = [[NSArray alloc] initWithArray:[newShareClasses sortedArrayUsingDescriptors:sortDescriptors]];

 

Please note, that if you sort strings, it is sorted as strings. So if values are 1,2,3…10 …it is sorted:  1,10,2,3,4,5 ….

If you want to sort your array using integer values of strings you can write your own comparator (read about NSComparisonResult) or you can use “tricky” NSNumericSearch function inside your sortDescriptor:

NSSortDescriptor *codeDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"code" ascending:YES selector:@selector(caseInsensitiveCompare:) comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; } ] autorelease];
This is the fastest method and you don't need to convert your string to integer for comparison.

 

Tags: