NSPredicate for multiple objects and properties

I have the following extension method for searching an array:

- (NSArray *)searchItemsForTerm:(NSString *)term;
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", term];
    return [[self filteredArrayUsingPredicate:resultPredicate] copy];
}

      

Sometimes not all of my objects in an array have a "name" property. In this case, I am getting an exception. Is there a way to create this predicate that can ignore any non-existent properties?

Thank!

+3


source to share


1 answer


Something like:



- (NSArray *)searchItemsForTerm:(NSString *)term;
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", term];
    NSArray *filteredArray = [self filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([evaluatedObject respondsToSelector:@selector(name)]) {
            return [resultPredicate evaluateWithObject:evaluatedObject];
        }
        return NO;
    }]];

    return filteredArray;
}

      

+2


source







All Articles