Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...