具有函数或选择器的NSPredicate [英] NSPredicate with functions or selectors

查看:113
本文介绍了具有函数或选择器的NSPredicate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多人NSManagedObjects,我需要过滤,并希望在初始提取,而不是过滤数组后。我在谓词中使用了选择器,但从来没有,当提取NSManagedObjects,例如我有所有的员工,然后我使用这个谓词在NSArray ...

  [NSPredicate predicateWithFormat:@SELF isKindOfClass:%@,[Boss class]] 

...但现在我想根据我的对象的不同属性做一些更多的数学。我想我可以做像... ...

  [NSPredicate predicateWithFormat:@SELF bonusIsAffordable:%f,howMuchMoneyTheCompanyHas]; 

..其中bonusIsAffordable:是我的Employee类的一个方法,并计算是否能够支付他们的奖金。但我收到一个错误...

 未知/不支持的比较谓词运算符类型可可
解决方案

>



当在内存中限定对象时,您只能在NSPredicate 中执行任意代码。在SQLite支持的 NSPersistentStore 的情况下, NSPredicate 被编译为SQL并在SQLite查询引擎上执行。因为SQLite没有Objective-C的知识,也没有任何对象实例化,没有办法执行任意代码。



对于内存查询内存中或原子核心数据存储),请查看 NSExpression ,特别是 + [NSExpression expressionForFunction:selectorName:arguments:] + [NSExpression expressionForBlock:arguments:] 。给定这样的表达式,您可以编程创建 NSPredicate


I have a lot of people NSManagedObjects that I need filtering and was hoping to do it within the initial fetch instead of filtering the array afterwards. I've used selectors in predicates before, but never when fetching NSManagedObjects, for example I have all my employees and then i use this predicate on the NSArray...

[NSPredicate predicateWithFormat:@"SELF isKindOfClass:%@", [Boss class]]

...but now I want to do a bit more math based on different attributes of my objects. I thought I could do something like...

[NSPredicate predicateWithFormat:@"SELF bonusIsAffordable:%f", howMuchMoneyTheCompanyHas];

..where bonusIsAffordable: is a method of my Employee class and would calculate whether I can afford to pay them a bonus. But I get an error...

Unknown/unsupported comparison predicate operator type cocoa

Any ideas what I'm screwing up?

解决方案

You can execute arbitrary code in an NSPredicate only when qualifying objects in memory. In the case of a SQLite-backed NSPersistentStore, the NSPredicate is compiled to SQL and executed on the SQLite query engine. Since SQLite has no knowlege of Objective-C, nor are any objects instantiated, there's no way to execute arbitrary code.

For in-memory queries (against a collection or an in-memory or atomic Core Data store), have a look at NSExpression, particular +[NSExpression expressionForFunction:selectorName:arguments:] and +[NSExpression expressionForBlock:arguments:]. Given such an expression, you can build an NSPredicate programatically.

这篇关于具有函数或选择器的NSPredicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆