NSPredicate with boolean is not comparing a boolean to NO

Christian Schlensker picture Christian Schlensker · Aug 26, 2011 · Viewed 9.7k times · Source

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?

Answer

Ben Mosher picture Ben Mosher · Aug 26, 2011

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.