【问题标题】:Add additional argument to an existing NSPredicate向现有的 NSPredicate 添加附加参数
【发布时间】:2011-05-27 10:29:00
【问题描述】:

是否可以采用现有的 NSPredicate 并向其添加额外的参数?

在我的一个表视图中,我传递了一个 NSPredicate 以用于我的 NSFetchedResultsController,如下所示:

[fetchedResults setPredicate:self.predicate];

这工作得很好,将根据现有的 NSPredicate 显示内容。但我想通过向 tableView 添加一个 UISegmentedControl 来更进一步。

- (IBAction)segmentChange:(id)sender {
     switch (selectedSegment) {
            case kDisplayDVD:
                // Add argument to existing NSPredicate
                break;
            case kDisplayVHS:
                // Add argument to existing NSPredicate
                break;
            default:
                break;
        }

根据用户选择的细分,我想为现有的 NSPredicate 添加一个参数。这有可能吗?

【问题讨论】:

    标签: iphone core-data nsfetchedresultscontroller nspredicate


    【解决方案1】:

    当然!

    假设您的对象有一个名为 display 的属性,它是一个 int(或者更确切地说,一个对应于您的 kDisplayDVDkDisplayVHS 等的枚举)。然后你可以这样做:

    - (IBAction) segmentChange:(id)sender {
      NSPredicate * newCondition = [NSPredicate predicateWithFormat:@"display = %d", selectedSegment];
      NSPredicate * newPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:[self predicate], newCondition, nil]];
      [self setPredicate:newPredicate];
    }
    

    所以如果[self predicate](foo = @"bar" OR baz > 42),你的新谓词将是display = 1 AND (foo = @"bar" OR baz > 42)

    【讨论】:

    • 完美运行。非常感谢,对子谓词一无所知。
    • @avenged 不客气! NSPredicate 是我在 Foundation.framework 中最喜欢的东西之一 :)
    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多