【问题标题】:how to sort an NSArray of nested NSArrays by array count?如何按数组计数对嵌套 NSArray 的 NSArray 进行排序?
【发布时间】: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


    【解决方案1】:

    有几种解决方案,其中之一是:

    NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"@count"
                                                         ascending:YES];
    NSArray *sds = [NSArray arrayWithObject:sd];
    NSArray *sortedArray = [array sortedArrayUsingDescriptors:sds];
    

    【讨论】:

    • @Sam 确实如此,您始终可以将@count 集合运算符用于符合 KVC 的集合。
    • 啊,抱歉。我不知道/误读了您的代码。很酷!
    • 效果很好!...我在问问题之前尝试过,但我使用@"count" 作为密钥,它崩溃了...@"@count" 的秘密是什么???
    • @KDaker NSArray 没有名为 count 的 KVC 兼容密钥。有一个名为 -count 的实例方法,但它不是 KVC 意义上的键。也就是说,在 Cocoa 集合中,您可以使用称为 collection operators 的特殊键路径,@count 就是其中之一。
    【解决方案2】:
    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开头的?你是谁,你对贾斯汀做了什么?
    • ugggghhhhhhhhhh!!!!!!! =p 贾斯汀今天头疼,构建完成了。感谢您指出这一点——我现在已经修好了 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2015-07-15
    • 1970-01-01
    相关资源
    最近更新 更多