#利用数组的sortedArrayUsingComparator调用 NSComparator
当中NSComparator事实上就是一个返回NSComparisonResult的block。
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2); 当中obj1、obj2事实上是NSArray中的元素
resultArray = [arrayDic <span style="color:#009900;">sortedArrayUsingComparator:</span>^NSComparisonResult(id obj1, id obj2) { NSNumber * number1 = [[obj1 allKeys] objectAtIndex:0]; NSNumber * number2 = [[obj2 allKeys] objectAtIndex:0]; NSComparisonResult result = [number1 compare:number2]; return result == NSOrderedAscending; }];
#利用数组的sortedArrayUsingFunction 调用 相应方法customSort
NSInteger <span style="color:#ff9900;">sortByID</span>(id obj1, id obj2, void *context){ NSString *str1 =(NSString*) obj1; // ibj1 和 obj2 来自与你的数组中,事实上,个人认为是苹果自己实现了一个冒泡排序给大家使用 NSString *str2 =(NSString *) obj2; if (str1.length < str2.length) { <span style="white-space:pre"> </span>return NSOrderedDescending; } else if(str1.length == str2.length) { <span style="white-space:pre"> </span>return NSOrderedSame; } <span style="white-space:pre"> </span>return NSOrderedAscending; }
NSArray *sortedArray =[arr sortedArrayUsingFunction:sortByID context:nil];
#利用数组的sortedArrayUsingSelector调用 相应的SEL的方法
注意selector的方法是对数组元素而言的方法,假如数据元素没有compare:方法。能够通过扩展数组元素的类添加对应的方法。
NSMutableArray *arrayDic = [NSMutableArray arrayWithObjects: [NSDictionary dictionaryWithObjectsAndKeys:@"Obj0", [NSNumber numberWithInt:0], nil], [NSDictionary dictionaryWithObjectsAndKeys:@"Obj5", [NSNumber numberWithInt:5], nil], [NSDictionary dictionaryWithObjectsAndKeys:@"Obj2", [NSNumber numberWithInt:2], nil], [NSDictionary dictionaryWithObjectsAndKeys:@"Obj3", [NSNumber numberWithInt:3], nil], [NSDictionary dictionaryWithObjectsAndKeys:@"Obj1", [NSNumber numberWithInt:1], nil], [NSDictionary dictionaryWithObjectsAndKeys:@"Obj4", [NSNumber numberWithInt:4], nil], nil]; #ifdef sortedArrayUsingSelector resultArray = [arrayDic sortedArrayUsingSelector:@selector(compare:)];
由于数组中元素相应的是字典,所以对字典的类进行扩展
@implementation NSDictionary (extend) - (NSComparisonResult)compare: (NSDictionary *)otherDictionary { NSNumber *number2 = [[otherDictionary allKeys] objectAtIndex:0]; NSDictionary *tempDictionary = (NSDictionary *)self; NSNumber *number1 = [[tempDictionary allKeys] objectAtIndex:0]; NSComparisonResult result = [number1 compare:number2]; // return result == NSOrderedDescending; // 升序 return result == NSOrderedAscending; // 降序 }
#利用数组的sortUsingDescriptors调用NSSortDescriptor
NSSortDescriptor 能够简单的理解为 指定对象的某属性的比較描写叙述。
}
本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5120708.html,如需转载请自行联系原作者