16

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?

Ben Mosher
  • 13,251
  • 7
  • 69
  • 80
Christian Schlensker
  • 21,708
  • 19
  • 73
  • 121

1 Answers1

28

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.

Kyle Redfearn
  • 2,172
  • 16
  • 34
Ben Mosher
  • 13,251
  • 7
  • 69
  • 80
  • I may be wrong, but I am pretty sure you need double equals instead of single equals in your solution. – TPoschel Nov 02 '12 at 00:22
  • 4
    `NSPredicate` syntax is more like SQL; since there is no need for an assignment operator, `=` and `==` are equivalent. See http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-SW1. – Ben Mosher Nov 02 '12 at 13:28
  • And for some really weird reason: http://stackoverflow.com/questions/5749426/how-do-i-set-up-a-nspredicate-to-look-for-objects-that-have-a-nil-attribute#7799907 – rwyland Dec 23 '13 at 18:45
  • 1
    Is there a difference between doing `[NSPredicate predicateWithFormat:@"deleted = NO"]` versus `[NSPredicate predicateWithFormat:@"deleted = %@", [NSNumber numberWithBool:NO]]`? – Kyle Redfearn Mar 04 '14 at 21:56