如何根据对象的属性对数组进行排序?
我有一个包含以下属性如何根据对象的属性对数组进行排序?
-name
-id
-type (question, topic or user)
我如何排序这个数组通用对象的基于通用对象的类型“通用对象”的NSArray的?例如。我想在顶部显示'主题'类型的所有通用对象,然后是'用户'而不是'问题'
您需要定义一个自定义排序函数,然后将其传递给允许自定义的NSArray方法排序。例如,使用sortedArrayUsingFunction:context:
,你可能会写(假设你的类型的NSString实例):
NSInteger customSort(id obj1, id obj2, void *context) {
NSString * type1 = [obj1 type];
NSString * type2 = [obj2 type];
NSArray * order = [NSArray arrayWithObjects:@"topic", @"users", @"questions", nil];
if([type1 isEqualToString:type2]) {
return NSOrderedSame; // same type
} else if([order indexOfObject:type1] < [order indexOfObject:type2]) {
return NSOrderedDescending; // the first type is preferred
} else {
return NSOrderedAscending; // the second type is preferred
}
}
// later...
NSArray * sortedArray = [myGenericArray sortedArrayUsingFunction:customSort
context:NULL];
如果你的类型不NSString的,然后根据需要只适应的功能 - 你可以在order
阵列替换字符串与您的实际对象或(如果您的类型是枚举的一部分)进行直接比较并完全消除order
阵列。
您也可以使用NSArray的'sortedArrayUsingComparator:'方法,它将块作为参数。这样可以避免需要编写自定义函数,因为您可以在块中放入相同的比较代码。 – 2012-01-09 03:03:13
@AndrewMadsen:很好,谢谢!在NSArray上实际上有一个类似的比较函数(好的,五个) - 我非常随意地选择了这个函数。珍:用你最舒服的方式。 – Tim 2012-01-09 03:05:06
这已经被回答了几次:[here](http://stackoverflow.com/questions/1351182/how-to-sort-a-nsarray-alphabetically),[here](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray -with-custom-objects-in-it)和[here](http://stackoverflow.com/questions/1844031/how-to-sort-nsmutablearray例如,使用描述符的使用排序的阵列)。 – user1118321 2012-01-09 02:48:07
这个问题可能有你的答案:[链接](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it) – jonkroll 2012-01-09 02:49:30
谢谢,但在我的情况下,我想特别推动所有类型=主题的对象顶部,所以我不能真正使用升序或降序排序在这种情况下,我想。我怎样才能做到这一点? – Zhen 2012-01-09 02:58:30