我需要能够对我的排序方法的结果进行排序,但我不清楚如何做到这一点,我是否需要在以前的结果上再次运行类似的方法,或者可以在一种方法中完成?
这是我的方法
-(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;
}
类型被设置为"建筑",这将返回游戏中的所有建筑类型,但如果我希望这些结果按照名称的字母顺序排序怎么办?或者是根据建筑的黄金价值来排序的?
必须解析数组两次。NSPredicate不提供排序的方法。查看nspredate编程指南。我所做的实际上是快速扫描nspreate BNF语法,寻找排序操作符的明显迹象,比如ASC或DESC,但什么也没有。
同样,在SO上也有很多类似的问题:
- 如何排序nsprecate
- NSSortDescriptor和nspreate用于排序和过滤
要告诉getGameTemplateObjectOfType:
您希望如何对结果进行排序,您可以传递一些用于排序的键。例如:
-(NSArray *)getGameTemplateObjectOfType:(NSString *)type sortedByKey:(NSString *)key ascending:(BOOL)ascending;
但是这样做可能会使您的代码复杂化-您将不得不处理函数中键和类型的所有组合。(如果你不明白我在说什么,请告诉我)。
最后,它可能是你辞职你的过滤函数getGameTemplateObjectOfType:
只是:过滤。如果该函数的客户端希望以某种方式对结果排序,那么客户端可以这样做。然后你就会发现为什么苹果把这些功能分开了。
在你的代码中,如果[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;
}