Proud Member Proud Member - 2 months ago 5
iOS Question

How to write a BOOL predicate in Core Data?

I have an attribute of type

BOOL
and I want to perform a search for all managed objects where this attribute is
YES
.

For string attributes it is straightforward. I create a predicate like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName = %@", userName];


But how do I do this, if I have a bool attribute called selected and I want to make a predicate for this? Could I just do something like this?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"selected = %@", yesNumber];


Or do I need other format specifiers and just pass
YES
?

Answer

From Predicate Programming Guide:

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"];

You can also check out the Predicate Format String Syntax.