Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSDate within an NSPredicate

Is there a particular way to configure an NSPredicate to compare dates?

Essentially I have a Photo object that has an NSDate, lastViewed.

I'd like to configure an NSPredicate that will return all the Photo objects that have been viewed more recently than a specified time period - typically two days.

I'm obtaining the past date like so:

NSTimeInterval secondsPast = -172800;

NSDate * twoDaysPast = [NSDate dateWithTimeInterval:secondsPast sinceDate:[NSDate date]]; And configuring the NSPredicate thusly:

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

However I'm getting no results back and I'm not quite certain why.

I know that all my Photo objects have lastViewed set - it's set to a default value of now whenever the Photo is added to Core Data, so by default I should be seeing every Photo created as lastViewed will be more recent than my twoDaysPast NSDate.

Can I directly compare two instances of NSDate in this manner?

like image 696
Will Avatar asked Jun 11 '11 16:06

Will


1 Answers

I was successful using the NSDate class method dateWithTimeIntervalSinceNow: (and you can do that all in one line) as follows:

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

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

NSDate objects can be directly compared using the NSDate method compare:. Dates are based on amount of time since a typedef'd reference date, allowing a date to be thus greater or lesser than another date. This is described here.

like image 69
Justin-Nicholas Y. Toyama Avatar answered Oct 09 '22 11:10

Justin-Nicholas Y. Toyama