簡體   English   中英

如何按數組計數對嵌套 NSArray 的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM