2013-07-05 256 views
1

我有一個數組數組。子數組包含對象。我怎樣才能排序父數組中的這些子數組,以便他們排序的第一個數組是包含最多的對象到最後一個包含最少的對象的子數組?根據子數組對數組進行排序count

回答

4

對於這種情況,就足以實現一個簡單的比較:

NSArray* sortedArray= [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) 
{ 
    return [obj2 count] - [obj1 count]; 
}]; 

進一步解釋

NSComparisonResult是這樣的枚舉:

enum { 
    NSOrderedAscending = -1, 
    NSOrderedSame,    // 0 
    NSOrderedDescending  // +1 
}; 

所以減去兩個數組數你得到正確的順序,避免寫出通常無聊的if-then-els即對於可讀性,不要混淆想法初學者我添加了長版在這裏:

而且使用與@count收集運營商一種描述

NSArray* sortedArray= [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) 
{ 
    if([obj1 count] > [obj2 count]) 
     return NSOrderedAscending; 
    if([obj1 count] < [obj2 count]) 
     return NSOrderedDescending; 
    return NSOrderedSame; 
}]; 

另類優雅:

NSSortDescriptor* descriptor= [NSSortDescriptor sortDescriptorWithKey: @"@count" ascending: NO]; 
NSArray* sortedArray= [array sortedArrayUsingDescriptors: @[ descriptor ]]; 
+0

這也可以使用自定義排序描述符 – uchuugaka

+0

您不需要自定義排序描述符。只是'[NSSortDescriptor sortDescriptorWithKey:@「count」升序:YES]'。 –

+0

@KenThomases關鍵應該是@「@ count」,順序不應該是升序,他希望他們從較長的一個開始排序。 –

相關問題