Как отсортировать NSArray вложенных NSArrays по количеству массивов? - PullRequest
1 голос
/ 30 апреля 2011

У меня есть NSArray, который содержит вложенные NSArrays. Я ищу способ сортировки родительского массива по количеству объектов вложенных массивов в порядке возрастания. поэтому, если [array1 count] равно 4, [array2 count] равно 2 и [array3 count] равно 9, я получу: массив2, массив1, массив3 ...

Ответы [ 2 ]

9 голосов
/ 30 апреля 2011

Существует несколько решений, одно из которых:

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"@count"
                                                     ascending:YES];
NSArray *sds = [NSArray arrayWithObject:sd];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sds];
1 голос
/ 30 апреля 2011
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;
...