我有一个包含嵌套NSArrays的NSArray。我正在寻找一种方法来根据嵌套数组的对象数按升序对父数组进行排序。因此,如果[array1 count]
为4,[array2 count]
为2且[array3 count]
为9,我会得到:array2,array1,array3 ......
答案 0 :(得分:9)
有一些解决方案,其中之一是:
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"@count"
ascending:YES];
NSArray *sds = [NSArray arrayWithObject:sd];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sds];
答案 1 :(得分:1)
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;