Search code examples
cocoanspredicatekvc

Format string for NSPredicate with @avg collection operator


Is there a way to construct an NSPredicate so the following array can be filtered by average score larger than, say, 5?

NSArray *objs = @[
@{@"scores":@[@3, @5, @2]},
@{@"scores":@[@5, @2, @8, @9]},
@{@"scores":@[@7, @1, @4]}
];

I have tried various combinations, of which this one seemed the most promising (considering that the key path @avg.self works to obtain the average value of numbers in an array through normal KVC):

NSPredicate *pred = [NSPredicate predicateWithFormat:@"[email protected] > 5"];
NSArray     *filterd = [objs filteredArrayUsingPredicate:pred];

The runtime error I get is the following:

NSUnknownKeyException', reason: '[<__NSArrayI 0x10011b7c0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key avg.

This predicate string works: scores.@count > 3, so at least that collection operator can be used in a predicate.


Solution

  • If you change [email protected] > 5 to [email protected] > 5 it will work fine.