NSPredicate - filtering values based on a BOOLEAN stored value

From Apple's documentation:

Boolean Values

You specify and test for equality of Boolean values as illustrated in the following examples:

NSPredicate *newPredicate =
    [NSPredicate predicateWithFormat:@"anAttribute == %@", [NSNumber numberWithBool:aBool]];
NSPredicate *testForTrue =
    [NSPredicate predicateWithFormat:@"anAttribute == YES"];

However, something that caught me out:

Be sure to untick the Optional entity attribute and set a Default Value of YES or NO, otherwise the column will be empty (null?) and the above predicates will not match rows which are not explicitly set.

I used the great app sqllitebrowser to diagnose this one, by looking at the resulting simulator database.


This isn't really specific to NSPredicate... Whenever you have %@ in a format string, the corresponding value must be a pointer to an object, and BOOL doesn't qualify. So instead of passing YES, pass [NSNumber numberWithBool: YES].


In newer versions of Xcode and the SDKs than when I originally wrote the answer, you can use @YES instead of [NSNumber numberWithBool: YES].