NSPredicate 和 CoreData - 决定日期属性是否为“今天” (或昨晚 12 点到今晚 12 点之间)在 iOS 上
我使用 NSFetchedResultsController
和 UITableViewController
从 CoreData 数据库填充 UITableView。
我有一个 NSDate
对象保存到标记为“startTime”的日期属性中。然后,我尝试使用如下所示的 NSPredicate 来提取今天的数据:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startDate == %@",
todaysDate];
我得到的结果为零。我理解这一点是因为 NSDate
对象只保存自 1970 年 1 月 1 日以来的秒数或毫秒数,对吧?因此,在同一天比较 1111111111111 和 1111111111112 时,两个不同的 NSDate
对象不相等。
那么,如何格式化 NSPredicate 才能执行此操作呢?我猜测它会创建两个 NSDate
对象:一个是昨晚 12 点,另一个是今晚 12 点,然后比较 startDate,看看它是否在这两个 NSDate
之间s。
我对 NSPredicate
有点陌生,那么这是如何实现的呢?
I'm using a NSFetchedResultsController
and a UITableViewController
to populate a UITableView from a CoreData database.
I have a NSDate
object saved into this Date attribute labeled "startTime". Then I'm trying to only pull todays's data by using a NSPredicate
that looks like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startDate == %@",
todaysDate];
I'm getting zero results. I understand this because a NSDate
object just hold the number of seconds or milliseconds or whatever since Jan 1 1970 right? So comparing 1111111111111 and 1111111111112, while on the same day, are two distinct NSDate
objects that aren't equal.
So, how could the NSPredicate
be formatted so that it would do it? I'm going to guess its creating two NSDate
objects: one that is at 12am last night, and another for 12am tonight and compare startDate and see if its between these two NSDate
s.
I'm kind of new to NSPredicate
, so how could this be accomplished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 NSCompoundPredicate。
其中,
firstDate
是今天早上 12 点,secondDate
是今晚 12 点。PS 以下是获取今天早上 12 点的方法:
要获取今晚 12 点,请更改
components.day
。Use
NSCompoundPredicate
.Where
firstDate
is 12am this morning andsecondDate
is 12am tonight.P.S. Here's how to get 12am this morning:
To get 12am tonight, change
components.day
.