cfischer
cfischer

Reputation: 24902

Evaluating an NSPredicate on a NSArray (without filtering)

Is it possible to evaluate a NSPredicate on a NSArray, without having the NSPredicate starting to filter out objects in the array?

For instance, say I have the following predicate that just checks the number of objects in an array:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"count == 3"];
NSArray *list = [NSArray arrayWithObjects:@"uno", @"dos", @"volver", nil];
BOOL match = [pred evaluateWithObject:list];

This will crash, as pred will try to retrieve the "count" key from the first object in the array instead of the array itself.

Upvotes: 8

Views: 5028

Answers (3)

Dave DeLong
Dave DeLong

Reputation: 243146

An alternative to using [SIZE] in your predicate format string is to do this:

NSPredicate *p = [NSPredicate predicateWithFormat:@"@count = 3"];

@count is one of the simple collection keypath operators and is quite useful. It is far more common to use it than [SIZE], although both are fine.

Upvotes: 9

EmptyStack
EmptyStack

Reputation: 51374

Use the SIZE operator of NSPredicate which is equivalent to count method of NSArray.

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF[SIZE] == 3"];
NSArray *list = [NSArray arrayWithObjects:@"uno", @"dos", @"volver", nil];
BOOL match = [pred evaluateWithObject:list];

Upvotes: 14

Lloyd18
Lloyd18

Reputation: 1682

For example, you can create category with methods you need:

@interface NSPredicate (myCategory)
    - (BOOL)evaluateWithArray:(id)array;
    // other methods
@end

and in .m file implement it like this:

- (BOOL)evaluateWithArray:(id)array {
    if ([array isKindOfClass:[NSArray class]])
        return [self evaluateWithObject:array];
    return NO;
}

Hope, it helps.

Upvotes: 1

Related Questions