1.通过数组NSArray的方法sortedArrayUsingComparator进行排序,该方法通过代码块方式简单易行:
- (NSArray*)arraySortedByName
{
NSMutableArray* InfosForSort = [NSMutableArrayarrayWithArray:oldArray];
NSArray *newArray = [InfosForSort sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//修改以下内容选择指定的数据作为排序的参考
IssueInfo *info1 = (IssueInfo*)obj1;
IssueInfo *info2 = (IssueInfo*)obj2;
NSString *name1 = info1.name;
NSString *name2 = info2.name;
NSComparisonResult result = [name1 compare:name2];
return result == NSOrderedAscending; // 降序
}];
return newArray;
}
2.通过NSArray的方法,该方法通过复写compare或者自定义比较函数来实现排序:
NSArray *resultArray = [array sortedArrayUsingSelector:@selector(compare:)];
- - (NSComparisonResult)compare: (NSDictionary *)otherDictionary
- {
- NSDictionary *tempDictionary = oldDictionary;
- NSNumber *number1 = [[tempDictionary allKeys] objectAtIndex:0];
- NSNumber *number2 = [[otherDictionary allKeys] objectAtIndex:0];
- NSComparisonResult result = [number1 compare:number2];
- return result == NSOrderedDescending; // 升序
- // return result == NSOrderedAscending; // 降序
- }
暂时以上两种方法基本解决所有数组排序场景,以后遇到新的好用的方法再更新。