Question

Core Data NSPredicate checking for BOOL value

I am currently having an issue pulling all data from db whereby i.e 1 parameter is TRUE.

I am using NSPredicate and below is a sample code

NSManagedObjectContext *context = managedObjectContext_;

if (!context) {
    // Handle the error.
    NSLog(@"ERROR CONTEXT IS NIL");
}

NSEntityDescription *entity = [NSEntityDescription entityForName:@"tblcontent" inManagedObjectContext:managedObjectContext_];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bookmarked == YES"];

[request setPredicate:predicate];

I tried setting predicatewithformat to almost everything but it still does not pull out bookmarks which have a YES value.

I even tried (@"bookmarked == %d",YES) but with not luck. I don't want to have to get the whole array and then filter it manually by doing if(object.bookmarked == YES) .....blabla.

I will really appreciate some help.

Many thanks.

 45  38384  45
1 Jan 1970

Solution

 73

Based on Apple Document Here, we can use the following two methods to compare Boolean:

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

However, the above predicate cannot get out the ones with empty anAttribute. To deal with an empty attribute, you need the following method according to Apple document here:

predicate = [NSPredicate predicateWithFormat:@"firstName = nil"]; // it's in the document

or

predicate = [NSPredicate predicateWithFormat:@"firstName == nil"]; // == and = are interchangeable here
2012-01-09

Solution

 32

Sneaking in with the Swift 3/4 answer:

let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))

We have to use NSNumber apparently because a literal bool is not acceptable per Apple.

Stolen from here ;)

2017-11-16