问题
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