Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 758
user281300 Avatar asked Sep 08 '10 16:09

user281300


2 Answers

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 
like image 140
Mingming Avatar answered Sep 18 '22 17:09

Mingming


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 ;)

like image 33
davidrynn Avatar answered Sep 18 '22 17:09

davidrynn