在NSPredicate中使用NSDate [英] Using NSDate within an NSPredicate

查看:296
本文介绍了在NSPredicate中使用NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有特别的方法来配置NSPredicate来比较日期?

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

基本上我有一个Photo对象有NSDate,lastViewed。

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

我想配置一个NSPredicate,它将返回最近一段时间内被查看的所有Photo对象(通常为两天)。

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;

NSTimeInterval secondsPast = -172800;

NSDate * twoDaysPast = [NSDate dateWithTimeInterval:secondsPast sinceDate:[NSDate date]];

因此配置NSPredicate:

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.

我知道我的所有Photo对象都有lastViewed设置 - 它被设置为默认值现在每当照片被添加到Core Data,所以默认情况下我应该看到每个创建的照片lastViewed将是

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.

我可以用这种方式直接比较NSDate的两个实例吗?

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

推荐答案

这是在NSPredicates中使用NSDates的正确方法。如果它不工作,你尝试删除谓词,确保请求的其余部分工作?您也可能希望在运行查询之前通过NSLog查看谓词检查您的谓词。

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.

这篇关于在NSPredicate中使用NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆