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