ios - 排序 NSArray 和大小写优先级

标签 ios objective-c nsarray nspredicate

我有一个存储在核心数据中的托管对象列表。我使用这些对象来填充根据字母顺序分段的 TableView Controller 。这些对象中的数据是通过网络服务获得的,所以我无法控制它们的大小写(在这种情况下确实没有太大区别)。

大部分数据以全部大写形式返回。我注意到,在极少数情况下,情况并非全部大写,这些项目不会按字母顺序排列。在以下代码示例中,stationIndex 是一个排序后的首字母数组:

for(NSString *character in stationIndex){

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"name beginswith[c] %@", character];
    // sort the list
    NSArray *filteredGaugeList = [[tempGaugeList filteredArrayUsingPredicate:pred] sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSString *first = [(Gauge*)a name];
        NSString *second = [(Gauge*)b name];
        return [first compare:second];
    }];
    if([filteredGaugeList count] > 0){
        [[self allGauges] addObject:filteredGaugeList];
    }
}

我知道在使用选择器时有一种方法可以忽略大小写,但在我的例子中,我正在对对象的属性进行排序,所以我假设我需要一个比较器。在这种情况下有没有办法处理案件?谢谢!

最佳答案

您也可以在比较器中忽略大小写,只需使用

return [first caseInsensitiveCompare:second];

或者,使用指定选择器排序键的排序描述符:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name"
                           ascending:YES
                            selector:@selector(caseInsensitiveCompare:)];
NSArray *sorted = [array sortedArrayUsingDescriptors:@[sort]];

备注:要在 TableView 中显示 Core Data 对象,您还可以使用 NSFetchedResultsController。然后你会添加谓词和排序 获取请求的描述符。获取的结果 Controller 也有方法 将表格 View 分组,并自动更新表格 View 当插入/删除/修改对象时。

关于ios - 排序 NSArray 和大小写优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19846245/

相关文章:

ios - iOS框架找不到Texture Atlas

ios - 如何在 boundingRectWithSize 中指定 NSLineBreakMode?

ios - 分组 TableView - 了解选择了哪个单元格

ios - 如何以编程方式删除 Safari cookie

iphone - 如何在当前时间添加时间

ios - iOS 7 中的 UITabbarController 布局问题-导航栏后面的 View

ios - 数组不在 View Controller ios 之间传递

cocoa - 搜索具有 nsmutablearray 内容的字符串

iOS - bodyWithPolygonFromPath : Body is the same as the path but collisions are not working properly

objective-c - cocoa 用户界面分析