iOS几种简单有效的数组排序方法

第一种,利用数组的sortedArrayUsingComparator调用 NSComparator ,obj1和obj2指的数组中的对象

 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:@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",nil];

//排序前

  NSMutableString *outputBefore = [[NSMutableString alloc] init];
for(NSString *str in sortArray){
[outputBefore appendFormat:@"];
}
NSLog(@"排序前:%@",outputBefore);
[outputBefore release];

 第一种排序

  NSArray *array = [sortArray sortedArrayUsingComparator:cmptr];

  NSMutableString *outputAfter = [[NSMutableString alloc] init];
for(NSString *str in array){
[outputAfter appendFormat:@"];
}
NSLog(@"排序后:%@",outputAfter);
[outputAfter release];

第二种 排序方法 利用sortedArrayUsingFunction 调用 对应方法customSort,这个方法中的obj1和obj2分别是指数组中的对象。

 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;
}
NSArray *sortArray = [[NSArray alloc] initWithObjects:@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",nil];

//排序前

  NSMutableString *outputBefore = [[NSMutableString alloc] init];
for(NSString *str in sortArray){
[outputBefore appendFormat:@"];
}
NSLog(@"排序前:%@",outputBefore);
[outputBefore release]; NSArray *array = [sortArray sortedArrayUsingFunction:customSort context:nil]; NSMutableString *outputAfter = [[NSMutableString alloc] init];
for(NSString *str in array){
[outputAfter appendFormat:@"];
}
NSLog(@"排序后:%@",outputAfter);
[outputAfter release];

第三种 利用sortUsingDescriptors调用NSSortDescriptor

  NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:NO];//其中,price为数组中的对象的属性,这个针对数组中存放对象比较更简洁方便
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:];
[_totalInfoArray sortUsingDescriptors:sortDescriptors];
[_airListView refreshTable:_totalInfoArray];
[sortDescriptor release];
[sortDescriptors release];

(有些乱,以后会进一步整理)

上一篇:【佛山市选2013】JZOJ2020年8月7日提高组T3 海明距离


下一篇:Android OkHttp文件上传与下载的进度监听扩展