2013-04-27 91 views
0

我需要能夠排序我的排序方法的結果,但我不清楚如何做到這一點,我是否需要再次運行一個相似的方法對以前的結果或可以它用一種方法完成?排序結果Obj-c

這裏是我的方法

-(NSArray*)getGameTemplateObjectOfType:(NSString *) type 
{ 
    NSArray *sortedArray;  

    if(editorMode == YES) 
    { 
     sortedArray = kingdomTemplateObjects; 
    } 
    else 
    { 
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type CONTAINS[cd] %@", type]; 

     NSArray *newArray = [kingdomTemplateObjects filteredArrayUsingPredicate:predicate]; 

     NSSortDescriptor *sortDescriptor; 
     sortDescriptor = [[NSSortDescriptor alloc] initWithKey:type 
                ascending:YES]; 
     NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 

     sortedArray = [newArray sortedArrayUsingDescriptors:sortDescriptors]; 

    } 


    return sortedArray; 
} 

類型被設置爲返回在我遊戲中的所有建築類型,但如果我再想這些結果按照他們的名字字母順序進行排序「大廈」?或者可能根據哪個建築物的黃金價值來排序最高?

回答

1

你必須解析數組兩次。 NSPredicate不提供排序的方法。檢查出NSPredicate Programming Guide。我所做的實際上是快速掃描NSPredicate BNF Syntax以查找排序運算符的明顯跡象,例如ASC或DESC。沒有什麼。

此外,這裏還有上等等一些類似的問題:

要告訴你,你怎麼想要的結果getGameTemplateObjectOfType:排序,你可能會傳遞一些關鍵字進行排序。例如:

-(NSArray *)getGameTemplateObjectOfType:(NSString *)type sortedByKey:(NSString *)key ascending:(BOOL)ascending; 

但這樣做很可能你的代碼複雜化 - 你將不得不處理自己的函數中的關鍵和類型的所有組合。 (讓我知道如果你不明白我在這裏說的話)。

最後可能是您將過濾功能getGameTemplateObjectOfType:重新設置爲:過濾。如果該功能的客戶想要以某種方式排序結果,那麼客戶可以這樣做。然後你會發現蘋果爲什麼保持功能分離。

+0

對,所以這只是一個通過數組進行多次掃描的問題,方法稍有不同。 – Phil 2013-04-27 15:06:48

+0

是的。但是你的複雜性實際上並沒有增加,所以成本並不令人望而卻步。祝你好運! – QED 2013-04-27 15:07:47

1

在你的代碼中,如果[kingdomTemplateObjects filteredArrayUsingPredicate:predicate];返回正確的結果

然後你可以使用[newArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];排序你的數組。

-(NSArray*)getGameTemplateObjectOfType:(NSString *) type 
    { 
     NSArray *sortedArray;  

     if(editorMode == YES) 
     { 
      sortedArray = kingdomTemplateObjects; 
     } 
     else 
     { 
      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type CONTAINS[cd] %@", type]; 
      NSArray *newArray = [kingdomTemplateObjects filteredArrayUsingPredicate:predicate]; 
      sortedArray = [newArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
     } 


     return sortedArray; 
    }