NSPredicate with functions or selectors

I have many NSManagedObjects people that I need to filter, and was hoping to do this in the original selection, instead of filtering the array later. I used to use selectors in predicates, but never getting NSManagedObjects, for example, I have all my employees, and then I use this predicate for NSArray ...

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

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

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

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

 Unknown/unsupported comparison predicate operator type cocoa 

Any ideas what I'm screwing up?

+6
objective-c iphone cocoa core-data nspredicate
source share
3 answers

You can execute arbitrary code in NSPredicate only when defining objects in memory. In the case of the SQLite-backed NSPersistentStore , the NSPredicate compiled into SQL and executed on the SQLite query server. Since SQLite does not have knowledge about Objective-C, and no objects are created, there is no way to execute arbitrary code.

For in-memory queries (against an Atom or Atom data collection or storage), see NSExpression , especially +[NSExpression expressionForFunction:selectorName:arguments:] and +[NSExpression expressionForBlock:arguments:] . With this expression, you can programmatically create an NSPredicate .

+13
source share

This gets a lot easier with Blocks :

 NSPredicate *bossPred = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) { return [evaluatedObject isKindOfClass:[Boss class]]; }]; 
+14
source share

Your predicate string does not tell the predicate object what to do. The method supposedly returns a boolean, but the predicate does not know what to compare with this. You could also give him the predicate line "TRUE" and expect him to know what to do with him.

Try:

 [NSPredicate predicateWithFormat:@"(SELF bonusIsAffordable:%f)==YES", howMuchMoneyTheCompanyHas]; 
0
source share

All Articles