to check an coredata object is nil

纵然是瞬间 提交于 2019-12-06 17:56:26

问题


I want to find out the objects in the core data, my code:

Types:

signedDate (Date)

alarmDate(Date)

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

predicate is wrong ? How to judge an coredata object is nil? What the predicate should be?


回答1:


I don't think the predicate syntax calls for == nil. Use only one =

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

Your code above works right. It should be YES since it's nil.

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

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



回答2:


From apple docs

Testing for Null

If you want to match null values, you must include a specific test in addition to other comparisons, as illustrated in the following fragment.

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

By implication, a test for null that matches a null value returns true. In the following code fragment, ok is set to YES for both predicate evaluations.

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

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


来源:https://stackoverflow.com/questions/10245958/to-check-an-coredata-object-is-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!