J'ai un NSArray qui contient NSArrays nested. Je cherche un moyen de sortinger le tableau parent en fonction du nombre d'objects des arrays nesteds dans l'ordre croissant. donc si [array1 count]
est 4, [array2 count]
est 2 et [array3 count]
est 9, j'obtiendrais: array2, array1, array3 …
Il y a quelques solutions, dont l'une est:
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;