检查核心数据对象是否为零

时间:2012-04-20 12:08:31

标签: ios core-data nspredicate

我想找出核心数据中的对象,我的代码:

类型:

signedDate(日期)

alarmDate(日期)

starTime(NSDate)

endTime(的NSDate)

NSString *str = @"(signedDate >= %@) AND (signedDate < %@) AND (alarmDate == nil)";
NSPredicate *predicate = [NSPredicate predicateWithFormat:str, starTime, endTime];
[request setPredicate:predicate];
NSArray *results=[context executeFetchRequest:request error:nil];

谓词错了? 如何判断coredata对象是否为零? 谓词应该是什么?

2 个答案:

答案 0 :(得分:22)

我不认为谓词语法要求== nil。 只使用一个=

NSString *str = @"(signedDate >= %@) AND (signedDate < %@) AND (alarmDate = nil)";

上面的代码工作正常。它应该是YES,因为它是零。

BOOL ok;
predicate = [NSPredicate predicateWithFormat:@"firstName = nil"];
ok = [predicate evaluateWithObject:[NSDictionary dictionary]];

ok = [predicate evaluateWithObject:
[NSDictionary dictionaryWithObject:[NSNull null] forKey:@"firstName"]]; 

答案 1 :(得分:9)

来自apple docs

测试空

如果要匹配空值,除了其他比较之外,还必须包含特定测试,如以下片段所示。

predicate = [NSPredicate predicateWithFormat:@"(firstName == %@) || (firstName = nil)", firstName];
filteredArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"filteredArray: %@", filteredArray);

// Output:
// filteredArray: ( { lastName = Turner; }, { birthday = 1972-03-23 20:45:32 -0800; firstName = Ben; lastName = Ballard; }

通过暗示,与null值匹配的null测试返回true。在以下代码片段中,对于两个谓词评估,ok都设置为YES。

BOOL ok;
predicate = [NSPredicate predicateWithFormat:@"firstName = nil"];
ok = [predicate evaluateWithObject:[NSDictionary dictionary]];

ok = [predicate evaluateWithObject:
    [NSDictionary dictionaryWithObject:[NSNull null] forKey:@"firstName"]];