【发布时间】:2011-04-29 23:54:52
【问题描述】:
我有一个包含嵌套 NSArray 的 NSArray。我正在寻找一种方法来根据嵌套数组的对象计数以升序对父数组进行排序。所以如果[array1 count] 是 4,[array2 count] 是 2,[array3 count] 是 9,我会得到:array2,array1,array3...
【问题讨论】:
标签: iphone objective-c ios nsmutablearray nsarray
我有一个包含嵌套 NSArray 的 NSArray。我正在寻找一种方法来根据嵌套数组的对象计数以升序对父数组进行排序。所以如果[array1 count] 是 4,[array2 count] 是 2,[array3 count] 是 9,我会得到:array2,array1,array3...
【问题讨论】:
标签: iphone objective-c ios nsmutablearray nsarray
有几种解决方案,其中之一是:
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"@count"
ascending:YES];
NSArray *sds = [NSArray arrayWithObject:sd];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sds];
【讨论】:
@count 集合运算符用于符合 KVC 的集合。
@"count" 作为密钥,它崩溃了...@"@count" 的秘密是什么???
NSArray 没有名为 count 的 KVC 兼容密钥。有一个名为 -count 的实例方法,但它不是 KVC 意义上的键。也就是说,在 Cocoa 集合中,您可以使用称为 collection operators 的特殊键路径,@count 就是其中之一。
static NSInteger MONSortObjectsAscendingByCount(id lhs, id rhs, void* ignored) {
/* error checking omitted */
const NSUInteger lhsCount = [lhs count];
const NSUInteger rhsCount = [rhs count];
if (lhsCount < rhsCount) {
return NSOrderedAscending;
}
else if (lhsCount > rhsCount) {
return NSOrderedDescending;
}
else {
return NSOrderedSame;
}
}
/* use if mutable, and you wnat it sorted in place */
- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;
/* else use */
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;
【讨论】:
MON开头的?你是谁,你对贾斯汀做了什么?