Will
Will

Reputation: 581

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?

Upvotes: 6

Views: 9661

Answers (2)

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.

Upvotes: 5

Ben Gottlieb
Ben Gottlieb

Reputation: 85522

That is the proper way to use NSDates in NSPredicates. If it's not working, have you tried removing the predicate altogether and making sure the rest of the request works? You also might want to sanity check your predicate by NSLog'ing it before running the query.

Upvotes: 2

Related Questions