- (void) sortMethod {
NSComparator cmptr = ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult) NSOrderedSame;
};
NSArray *sortArray = [[NSArray alloc] initWithObjects:@"1",@"3",@"4",@"7",@"8",@"2",@"6",@"5",@"13",@"15",@"12",@"20",@"28",@"",nil];
//排序前
NSLog(@"排序前:%@",[self formatOutPut:sortArray]);
//第一种排序
NSArray * array = [sortArray sortedArrayUsingComparator:cmptr];
NSLog(@"排序后:%@",[self formatOutPut:array]);
//第二种排序:利用sortedArrayUsingFunction 调用 对应方法customSort,这个方法中的obj1和obj2分别是指数组中的对象。
array = [sortArray sortedArrayUsingFunction:customSort context:nil];
NSLog(@"排序后:%@",[self formatOutPut:array]);
}
- (NSString *) formatOutPut:(NSArray *) array {
NSMutableString * output = [[NSMutableString alloc] init];
for (NSString * str in array) {
[output appendFormat:@"%@ ",str];
}
return [output autorelease];
}
NSInteger customSort(id obj1, id obj2,void* context){
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};