Search code examples
objective-ccore-datansdatenspredicatensfetchedresultscontroller

Core data fetch predicate for NSDate


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.


Solution

  • 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.