Using NSDate in NSPredicate

Is there a way to configure NSPredicate to compare dates?

Essentially, I have a photo object that has NSDate, lastViewed.

I would like to configure NSPredicate, which will return all Photo objects that were viewed most recently than the specified time period - usually two days.

I get the past date as follows:

NSTimeInterval secondsPast = -172800;

NSDate * twoDaysPast = [NSDate dateWithTimeInterval: secondsPast sinceDate: [NSDate date]]; And setting up NSPredicate this way:

request.predicate = [NSPredicate predicateWithFormat:@"lastViewed > %@", twoDaysPast];

However, I am not getting any results, and I do not quite understand why.

I know that all my objects with a photo have a lastViewed set - now it is set to the default when the photo is added to Core Data, so by default I should see that each photo is created, since lastViewed will be later than my twoDaysPast NSDate .

Is it possible to directly compare two instances of NSDate this way?

+6
source share
2 answers

This is the correct way to use NSDates in NSPredicates. If it does not work, did you try to remove the predicate altogether and make sure that the rest of the request works? You may also want to check your NSLog'ing predicate before running the query.

+2
source

I managed to use the NSDate class NSDate dateWithTimeIntervalSinceNow: (and you can do it all on one line) as follows:

 request.predicate = [NSPredicate predicateWithFormat:@"recentPhotoLastViewed > %@", [NSDate dateWithTimeIntervalSinceNow:(-172800)]]; 

Make sure that the lastViewed objects in CoreData are actually NSDate objects, not strings.

The objects

NSDate can be directly mapped using the NSDate compare: method. Dates are based on the amount of time since typedef'd fingerprints, which allows you to make the date this way larger or smaller than another date. This is described here .

+4
source

Source: https://habr.com/ru/post/890296/