Format string for NSPredicate with @avg collection operator
Asked Answered
C

2

1

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.

Codeclination answered 3/5, 2013 at 12:38 Comment(0)
H
1

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

Hoon answered 3/5, 2013 at 21:44 Comment(0)
S
0

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/

Steffin answered 18/2, 2016 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.