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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With