Format string for NSPredicate with @avg collection operator

别等时光非礼了梦想. 提交于 2019-12-11 04:23:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!