核心数据NSPredicate检查BOOL值

use*_*300 32 database iphone core-data objective-c nspredicate

我目前在从db中提取所有数据时遇到问题,即1参数为TRUE.

我正在使用NSPredicate,下面是一个示例代码

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];
Run Code Online (Sandbox Code Playgroud)

我尝试将predicatewithformat设置为几乎所有内容,但它仍然没有拉出具有YES值的书签.

我甚至试过(@"bookmarked == %d",YES)但没有运气.我不想得到整个数组,然后通过做if(object.bookmarked == YES)..... blabla 手动过滤它.

我真的很感激一些帮助.

非常感谢.

Min*_*ing 60

基于Apple Document Here,我们可以使用以下两种方法来比较布尔值:

NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"anAttribute == %@",[NSNumber numberWithBool:aBool]];
NSPredicate *testForTrue = [NSPredicate predicateWithFormat:@"anAttribute == YES"];
Run Code Online (Sandbox Code Playgroud)

但是,上面的谓词不能得出那些空的anAttribute.为了应对空的属性,你需要根据苹果文档下面的方法在这里:

predicate = [NSPredicate predicateWithFormat:@"firstName = nil"]; // it's in the document
Run Code Online (Sandbox Code Playgroud)

要么

predicate = [NSPredicate predicateWithFormat:@"firstName == nil"]; // == and = are interchangeable here
Run Code Online (Sandbox Code Playgroud)


Dan*_*ney 12

出于某种原因,Flow的解决方案对我不起作用:

NSPredicate *testForTrue = [NSPredicate predicateWithFormat:@"anAttribute == YES"];
Run Code Online (Sandbox Code Playgroud)

但是,这样做了:

NSPredicate *testForTrue = [NSPredicate predicateWithFormat:@"anAttribute == 1"];
Run Code Online (Sandbox Code Playgroud)


Pat*_*ick 10

我迟到了派对,正如使用0和1讨论的那样,但是有一种更好的方法可以通过使用NSNumber BOOL文字来显示它,如@YES或@NO.它将其转换为1或0,但在视觉上更友好.

NSPredicate *testForTrue = [NSPredicate predicateWithFormat:@"anAttribute == %@", @NO];
Run Code Online (Sandbox Code Playgroud)


dav*_*ynn 6

偷偷用Swift 3/4的答案:

let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))
Run Code Online (Sandbox Code Playgroud)

显然,我们必须使用NSNumber,因为每个Apple都不接受字面意义上的布尔值。

从这里被盗;)


Nik*_*kov 5

当您为实体创建属性时,核心数据实体没有任何默认值,因此为了使谓词起作用,您应该为布尔属性设置默认值或以这种方式使用谓词。

如果您为实体的任何布尔属性提供默认值(NO 或 YES),则使用如下谓词

[NSPredicate predicateWithFormat:@"boolAttribute == %@", @NO];
[NSPredicate predicateWithFormat:@"boolAttribute == NO", @NO];
[NSPredicate predicateWithFormat:@"boolAttribute == %0"];
Run Code Online (Sandbox Code Playgroud)

如果您没有默认值或某些实体已创建而没有默认值,则要按错误值进行过滤,请使用以下句子:

[NSPredicate predicateWithFormat:@"boolAttribute == %@ || boolAttribute == nil", @NO];
Run Code Online (Sandbox Code Playgroud)


Jos*_*zzi 1

你还没有提到你得到了什么结果。代码清单中缺少两件事:设置请求实体的位置以及实际要求上下文执行获取请求的位置。我会从那里开始。

  • 哈哈,现在工作正常了。愚蠢的我忘记先从模拟器重置数据库了!!无论如何,上面的代码没问题。 (2认同)