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

别等时光非礼了梦想. 提交于 2019-12-19 10:55:10

问题


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...


回答1:


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



回答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;


来源:https://stackoverflow.com/questions/5838480/how-to-sort-an-nsarray-of-nested-nsarrays-by-array-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!