[英]How do I create an Objective-C NSDictionary of NSArrays without reusing the same NSArray?
[英]how to sort an NSArray of nested NSArrays by array count?
我有一个包含嵌套 NSArray 的 NSArray。 我正在寻找一种方法来根据嵌套 arrays 的 object 计数按升序对父数组进行排序。 所以如果[array1 count]
是 4, [array2 count]
是 2 而[array3 count]
是 9,我会得到:array2,array1,array3...
有几种解决方案,其中之一是:
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"@count"
ascending:YES];
NSArray *sds = [NSArray arrayWithObject:sd];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sds];
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.