Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate to filter out all items that are in another set

Is there any way to do this? I have a set of items that I want to exclude from another set. I know I could loop through each item in my set and only add it to my filteredSet if it's not in the other set, but it would be nice if I could use a predicate.

The set of items to exclude isn't a set of the same type of object directly; it's a set of strings; and I want to exclude anything from my first set if one of the attributes matches that string.... in other words:

NSMutableArray *filteredArray = [NSMutableArray arrayWithCapacity:self.questionChoices.count];

BOOL found;

for (QuestionChoice *questionChoice in self.questionChoices)
{
    found = NO;

    for (Answer *answer in self.answers)
    {
        if ([answer.units isEqualToString:questionChoice.code])
        {
            found = YES;
            break;
        }
    }

    if (!found)
        [filteredArray addObject:questionChoice];
}

Can this be done with a predicate instead?

like image 434
GendoIkari Avatar asked Dec 03 '10 17:12

GendoIkari


1 Answers

This predicate format string should work:

@"NONE %@.units == code", self.answers

Combine it with the appropriate NSArray filtering method. If self.questions is a regular immutable NSArray, it would look something like

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NONE %@.units == code", self.answers]

NSArray *results = [self.questions filteredArrayUsingPredicate:predicate];

If it's an NSMutableArray, the appropriate usage would be

[self.questions filterUsingPredicate:predicate];

Be careful with that last one though, it modifies the existing array to fit the result. You can create a copy of the array and filter the copy to avoid that, if you need to.

Reference:
NSArray Class Reference
NSMutableArray Class Reference
Predicate Programming Guide

like image 137
Endemic Avatar answered Oct 04 '22 17:10

Endemic