简体   繁体   中英

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

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 [array1 count] is 4, [array2 count] is 2 and [array3 count] is 9, i would get: array2, array1, array3...

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];
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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM