Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add additional argument to an existing NSPredicate

Is it possible to take an existing NSPredicate and add an additional argument to it?

In one of my tableviews I am passing in a NSPredicate to use in for my NSFetchedResultsController like so:

[fetchedResults setPredicate:self.predicate];

This is working just fine and will show the content based on the existing NSPredicate. But I want to take this one step further by adding an UISegmentedControl to the tableView.

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

Based on which segment the user has chosen I would like to add an argument to the existing NSPredicate. Is this at all possible?

like image 310
avenged Avatar asked Dec 18 '10 01:12

avenged


1 Answers

Sure!

Let's say that your objects have a property called display that's an int (or rather, an enum that corresponds to your kDisplayDVD, kDisplayVHS, etc). Then you can do:

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

So if [self predicate] is (foo = @"bar" OR baz > 42), your new predicate will be display = 1 AND (foo = @"bar" OR baz > 42)

like image 70
Dave DeLong Avatar answered Sep 18 '22 15:09

Dave DeLong