how to sort an NSArray of nested NSArrays by array count?

后端 未结 2 1051
你的背包
你的背包 2021-01-16 08:53

I have an NSArray that contains nested NSArrays. Im looking for a way to sort the parent array according to the object count of the nested arrays in ascending order. so if <

相关标签:
2条回答
  • 2021-01-16 09:32

    There are a few solutions, one of which is:

    NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"@count"
                                                         ascending:YES];
    NSArray *sds = [NSArray arrayWithObject:sd];
    NSArray *sortedArray = [array sortedArrayUsingDescriptors:sds];
    
    0 讨论(0)
  • 2021-01-16 09:37
    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;
    
    0 讨论(0)
提交回复
热议问题