问题
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:@"scores.@avg.self > 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.
回答1:
If you change scores.@avg.self > 5
to scores.@avg.doubleValue > 5
it will work fine.
回答2:
As @aLevelOfIndirection responded to you, you need to replace self
with doubleValue
because it's a number.
There are a good article explaining KVC operators in collections which would be useful to you: http://nshipster.com/kvc-collection-operators/
来源:https://stackoverflow.com/questions/16359155/format-string-for-nspredicate-with-avg-collection-operator