2013-04-27 86 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; 
    }