Using NSDate within an NSPredicate

送分小仙女□ 提交于 2019-12-21 12:49:14

问题


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?


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/6317240/using-nsdate-within-an-nspredicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!