Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 752
Proud Member Avatar asked May 29 '11 17:05

Proud Member


2 Answers

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.

like image 114
albertamg Avatar answered Nov 15 '22 14:11

albertamg


Swift 4.0

let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true)) 
like image 31
Viktor Kucera Avatar answered Nov 15 '22 14:11

Viktor Kucera