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

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

问题描述

我有很多需要过滤的 NSManagedObjects 对象,我希望在初始获取时进行过滤,而不是之后过滤数组.我之前在谓词中使用过选择器,但从未在获取 NSManagedObjects 时使用过选择器,例如我拥有我所有的员工,然后我在 NSArray 上使用了这个谓词...

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:是我的 Employee 类的一种方法,用于计算我是否有能力支付他们奖金.但我收到一个错误...

..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

知道我搞砸了什么吗?

推荐答案

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

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.

对于内存查询(针对集合或内存或原子核心数据存储),请查看 NSExpression,特别是 +[NSExpression expressionForFunction:selectorName:arguments:]code> 和 +[NSExpression expressionForBlock:arguments:].给定这样的表达式,您可以以编程方式构建 NSPredicate.

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天全站免登陆