【问题标题】:How to sort NSPredicate如何对 NSPredicate 进行排序
【发布时间】:2011-08-04 18:28:19
【问题描述】:

我正在尝试在使用 NSPredicate 时对数组进行排序。我已经阅读了其他可能使用 NSSortDescriptor 的地方。搞清楚这个有点麻烦。

我正在尝试按 companyName 对数组进行排序。

感谢任何建议,谢谢

格雷格

- (void)filterSummaries:(NSMutableArray *)all byNameThenBooth:(NSString*) text results:(NSMutableArray *)results
{
    [results removeAllObjects];

    if ((nil != text) && (0 < [text length])) {        
        if ((all != nil) && (0 < [all count])) {
            NSPredicate *predicate = [NSPredicate predicateWithFormat: @"companyName contains[cd] %@ OR boothNumber beginswith %@", text, text];
            [results addObjectsFromArray:[all filteredArrayUsingPredicate:predicate]];        
        }
    }
    else {
        [results addObjectsFromArray:all];
    }
}

【问题讨论】:

    标签: cocoa-touch cocoa nspredicate


    【解决方案1】:

    您有多种选择如何对数组进行排序:

    我将在这里展示一个基于 NSSortDescriptor 的方法。

    NSPredicate *predicate = [NSPredicate predicateWithFormat:
                                      @"companyName contains[cd] %@ OR boothNumber beginswith %@",
                                      text,
                                      text];
    
    // commented out old starting point :)
    //[results addObjectsFromArray:[all filteredArrayUsingPredicate:predicate]];
    
    // create a descriptor
    // this assumes that the results are Key-Value-accessible
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"companyName" 
                                                                 ascending:YES];
    //
    NSArray *results = [[all filteredArrayUsingPredicate:predicate]  
                         sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
    
    // the results var points to a NSArray object which contents are sorted ascending by companyName key
    

    这应该可以完成您的工作。

    【讨论】:

    • 感谢您的回复,我编辑了我的主要帖子以显示更多代码。谓词不需要在某处使用吗?
    • 当然。懒得打字 ||复制粘贴;)
    • 我可以使用 NSMutableArray 做到这一点吗?我有一个名为 results 的 NSMutableArray 作为参数传入。
    • 基本上是的。但是你会暂时失去可变性。之后您必须发送一个 mutableCopy 并且 - 最重要的是 - 通过适当地释放 mutableCopy(例如使用自动释放池)来遵守内存管理规则
    【解决方案2】:

    filteredArrayUsingPredicate: 函数遍历您的数组并将所有与谓词匹配的对象复制到一个新数组中并返回它。它不提供任何排序​​。这更像是一种搜索。

    使用 NSArray 的排序功能,即sortedArrayUsingComparator:sortedArrayUsingDescriptors:sortedArrayUsingFunction:context: 等,以最适合你的为准。

    结帐NSArray Class Reference了解详情。

    顺便说一句:如果你想按词法排序,你可以使用sortedArrayUsingSelector:@selector(compare:),它将使用 NSString 的compare: 函数来找到正确的顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 2011-11-09
      • 2014-04-18
      相关资源
      最近更新 更多