Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate with boolean is not comparing a boolean to NO

I'm using CoreData and my entity has a boolean property called "isReward".

I'm trying to fetch the entity and filter out all results where isReward == YES.

isReward != YES does not work.

isReward == NO does not work.

NSPredicate predicateWithFormat:"isReward != %@", [NSNumber numberWithBool:YES]] does not work

isReward == Nil works.

What gives?

like image 755
Christian Schlensker Avatar asked Aug 26 '11 20:08

Christian Schlensker


1 Answers

I'm guessing you'll want:

[NSPredicate predicateWithFormat:@"isReward = NO OR isReward = nil"]

(Per the Apple docs here, direct comparison to NO should be valid.)

In general, when comparing to null/nil in data terms, null == false evaluates to false and null != false evaluates false. Comparison to null generally evaluates to false, except when testing for IS NULL.

I would also say that indexing in general gives you better results when you search for equality, not inequality. This is fairly simple to refactor to in your case (though I'm not sure that it will matter to Core Data in general).

Also, if you would like it to always be YES or NO (and skip the check for nil), you need to explicitly set the default to NO.

However, you may have some semantic value in leaving it nil until it is explicitly set by your application. This is really up to what you're trying to do.

like image 191
Ben Mosher Avatar answered Oct 02 '22 17:10

Ben Mosher