Zhe*_*hen 2 sorting properties objective-c nsarray ios
我有一个'通用对象'的NSArray,它包含以下属性
-name
-id
-type (question, topic or user)
Run Code Online (Sandbox Code Playgroud)
如何根据泛型对象的类型对这个泛型对象数组进行排序?例如,我想在顶部显示"主题"类型的所有通用对象,然后是"用户"而不是"问题"
您需要定义自定义排序函数,然后将其传递给允许自定义排序的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];
Run Code Online (Sandbox Code Playgroud)
如果你的类型不是NSStrings,那么只需根据需要调整函数 - 你可以order
用你的实际对象替换数组中的字符串,或者(如果你的类型是枚举的一部分)做直接比较并order
完全消除数组.
归档时间: |
|
查看次数: |
1625 次 |
最近记录: |