是否有特定的方法来配置 NSPredicate 来比较日期?
基本上我有一个 Photo 对象,它有一个 NSDate,lastViewed。
我想配置一个 NSPredicate,它将返回最近查看的所有照片对象超过指定时间段 - 通常是两天。
我像这样获取过去的日期:
NSTimeInterval secondsPast = -172800;
NSDate * twoDaysPast = [NSDate dateWithTimeInterval:secondsPast sinceDate:[NSDate date]];
并这样配置 NSPredicate:
request.predicate = [NSPredicate predicateWithFormat:@"lastViewed > %@", twoDaysPast];
但是我没有得到任何结果,我也不太确定为什么。
我知道我所有的 Photo 对象都设置了 lastViewed - 每当将 Photo 添加到 Core Data 时,它都设置为默认值 now,所以默认情况下我应该看到创建为 lastViewed 的每张照片都比我的 twoDaysPast 更新NSDate.
我可以用这种方式直接比较两个 NSDate 实例吗?
最佳答案
我成功地使用了 NSDate
类方法 dateWithTimeIntervalSinceNow:
(您可以在一行中完成所有操作),如下所示:
request.predicate = [NSPredicate predicateWithFormat:@"recentPhotoLastViewed > %@", [NSDate dateWithTimeIntervalSinceNow:(-172800)]];
确保 CoreData 中的 lastViewed
对象实际上是 NSDate
对象而不是字符串。
NSDate
对象可以使用 NSDate
方法 compare:
直接进行比较。日期基于自 typedef 引用日期以来的时间量,因此允许一个日期大于或小于另一个日期。这是描述here .
关于iphone - 在 NSPredicate 中使用 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6317240/