NSPredicate to filter out all items that are in another set
Asked Answered
G

2

6

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?

Gilgilba answered 3/12, 2010 at 17:39 Comment(0)
D
7

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

Degas answered 3/12, 2010 at 19:25 Comment(1)
Awesome, "NONE" worked perfectly. What I was missing was that I didn't realize I could just pass in an Array or Set to the predicate format like you would any other object. Thanks!Gilgilba
S
0

Check out the example given by Apple for using predicates with arrays. It employs filteredArrayUsingPredicate.

Sidonius answered 3/12, 2010 at 18:57 Comment(2)
I know that I need to use filteredArrayUsingPredicate, but I don't know how a predicate can check if a different array contains a certain value.Gilgilba
Apologies, itchy trigger finger. Can you use a sub-query with a 2nd predicate, kind of like this: answerspice.com/c119/1665179/…?Sidonius

© 2022 - 2024 — McMap. All rights reserved.