排序陣列
排序陣列最靈活的方法是使用 sortedArrayUsingComparator:方法。這接受 ^ 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
例:
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);