第一种,利用数组的sortedArrayUsingComparator调用 NSComparator ,obj1和obj2指的数组中的对象
1 NSComparator cmptr = ^(id obj1, id obj2){ 2 if ([obj1 integerValue] > [obj2 integerValue]) { 3 return (NSComparisonResult)NSOrderedDescending; 4 } 5 6 if ([obj1 integerValue] < [obj2 integerValue]) { 7 return (NSComparisonResult)NSOrderedAscending; 8 } 9 return (NSComparisonResult)NSOrderedSame; 10 }; 11 12 NSArray *sortArray = [[NSArray alloc] initWithObjects:@"1",@"3",@"4",@"7",@"8",@"2",@"6",@"5",@"13",@"15",@"12",@"20",@"28",@"",nil];
//排序前
1 NSMutableString *outputBefore = [[NSMutableString alloc] init]; 2 for(NSString *str in sortArray){ 3 [outputBefore appendFormat:@"]; 4 } 5 NSLog(@"排序前:%@",outputBefore); 6 [outputBefore release];
第一种排序
1 NSArray *array = [sortArray sortedArrayUsingComparator:cmptr]; 2 3 NSMutableString *outputAfter = [[NSMutableString alloc] init]; 4 for(NSString *str in array){ 5 [outputAfter appendFormat:@"]; 6 } 7 NSLog(@"排序后:%@",outputAfter); 8 [outputAfter release];
第二种 排序方法 利用sortedArrayUsingFunction 调用 对应方法customSort,这个方法中的obj1和obj2分别是指数组中的对象。
1 NSInteger customSort(id obj1, id obj2,void* context){ 2 if ([obj1 integerValue] > [obj2 integerValue]) { 3 return (NSComparisonResult)NSOrderedDescending; 4 } 5 6 if ([obj1 integerValue] < [obj2 integerValue]) { 7 return (NSComparisonResult)NSOrderedAscending; 8 } 9 return (NSComparisonResult)NSOrderedSame; 10 } 11 NSArray *sortArray = [[NSArray alloc] initWithObjects:@"1",@"3",@"4",@"7",@"8",@"2",@"6",@"5",@"13",@"15",@"12",@"20",@"28",@"",nil];
//排序前
1 NSMutableString *outputBefore = [[NSMutableString alloc] init]; 2 for(NSString *str in sortArray){ 3 [outputBefore appendFormat:@"]; 4 } 5 NSLog(@"排序前:%@",outputBefore); 6 [outputBefore release]; 7 8 NSArray *array = [sortArray sortedArrayUsingFunction:customSort context:nil]; 9 10 NSMutableString *outputAfter = [[NSMutableString alloc] init]; 11 for(NSString *str in array){ 12 [outputAfter appendFormat:@"]; 13 } 14 NSLog(@"排序后:%@",outputAfter); 15 [outputAfter release];
第三种 利用sortUsingDescriptors调用NSSortDescriptor
1 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:NO];//其中,price为数组中的对象的属性,这个针对数组中存放对象比较更简洁方便 2 NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:1]; 3 [_totalInfoArray sortUsingDescriptors:sortDescriptors]; 4 [_airListView refreshTable:_totalInfoArray]; 5 [sortDescriptor release]; 6 [sortDescriptors release];
(有些乱,以后会进一步整理)