Sorting Arrays
suggest changeThe most flexible way to sort an array is sortedArrayUsingComparator:. It takes a block of the form ^NSComparisonResult(id obj1, id obj2).
Return Value Description
NSOrderedAscending obj1 comes before obj2
NSOrderedSame obj1 and obj2 have no order
NSOrderedDescending obj1 comes after obj2
Example:
NSArray *categoryArray = @[@"Apps", @"Music", @"Songs",
@"iTunes", @"Books", @"Videos"];
NSArray *sortedArray = [categoryArray sortedArrayUsingComparator:
^NSComparisonResult(id obj1, id obj2) {
if ([obj1 length] < [obj2 length]) {
return NSOrderedAscending;
} else if ([obj1 length] > [obj2 length]) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
NSLog(@"%@", sortedArray);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents