问题
I have entity with two NSDate properties:
@property NSDate *startTime;
@property NSDate *endTime;
I use it for creating the point events and the duration events. So, for the point events endTime
can be equal to nil.
And i want to fetch all entities with restriction: startTime >= minDate && endTime <= maxDate
But NSPredicate like:
NSDate *startTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"firstBound"];
NSDate *endTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"secondBound"];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(startTime >= %@) AND ((endTime <= %@) OR (endTime == nil))",startTime,endTime]];
Does not work correctly. I`ll explain. If all the events stored in the database are in the range 2000-2010 year, and I'm doing a fetch with minDate = 1900, maxDate = 1950 EVERYTHING the point events from the database fit this predicate, because they endTime field is nil, and the field startTime clearly more than minDate.
Any idea how to handle this? Do not be limited by the NSPredicate. I will approach any decision.
回答1:
Presumably you want:
"((endTime != nil) and (startTime >= %@) and (endTime <= %@)) or
((endTime = nil) and (startTime >= %@) and (startTime <= %@))",
startTime, endTime, startTime, endTime
Though it'd be easier if you'd store instantaneous events as just having the same start and end time.
回答2:
I was facing the same issue. But got it resolved. Core data itself stores the NSDate in time interval format. When you pass the NSDate
as a parameter for a predicate, The predicate will type cast it to Time Interval and does its comparison. I did the same But It got failed to return the results. So Explicitly converting the date to time interval is worked.
I wanted to get list of items which as createdDate
less than maxCreatedDate
and less than minCreatedDate
For my issue I used like as follows:
[NSPredicate predicateWithFormat:@"createdDate >= %f AND createdDate <= %f", [minCreatedDate timeIntervalSince1970], [maxCreatedDate timeIntervalSince1970]];
This worked for me. You can try this:
[NSPredicate predicateWithFormat:@"(startTime >= %f) AND ((endTime <= %f) OR (endTime == nil))",[startTime timeIntervalSince1970], [endTime timeIntervalSince1970]];
来源:https://stackoverflow.com/questions/19363500/core-data-fetch-predicate-for-nsdate