1.子母排序
NSArray *kArrSort = [_dic allKeys]; //這裡是字母陣列:,g,a,b.y,m……
NSArray *resultkArrSort = [kArrSort sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSLog(@"%@",resultkArrSort);
2.數值排序
// sortedArrayUsingComparator:方法並不會改變array陣列內部的順序
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSNumber *obj1, NSNumber *obj2) {
if ([obj1 intValue] < [obj2 intValue]) {
return NSOrderedDescending;
} else {
return NSOrderedAscending;
} }];
NSLog(@"%@", sortedArray);
3.使用NSDescriptor進行排序
我們將要排序的物件是一個Persion類,如下定義:
- @interface Person : NSObject
- @property (nonatomic, copy) NSString *name;
- @property (nonatomic, copy) NSString *surname;
- @property (nonatomic, strong) NSDate *dateOfBirth;
- @end
而陣列中包含如下內容:
- Smith John 03/01/1984
- Andersen Jane 16/03/1979
- Clark Anne 13/09/1995
- Smith David 19/07/1981
- Johnson Rose 22/02/1989
- NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"surname" ascending:YES];
- NSSortDescriptor *secondDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
- NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, secondDescriptor, nil];
- NSArray *sortedArray = [self.persons sortedArrayUsingDescriptors:sortDescriptors];
上面程式碼的排序結果如下所示:
- Andersen Jane
- Clark Anne
- Johnson Rose
- Smith David
- Smith John