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 (开发者_C百科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?
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)
精彩评论