【问题标题】:NSPredicate and CoreData - decide if a Date attribute is "today" (or between last night 12am to tonight 12am) on iOSNSPredicate 和 CoreData - 决定 iOS 上的 Date 属性是否为“今天”(或昨晚 12 点到今晚 12 点之间)
【发布时间】:2012-03-13 04:11:24
【问题描述】:

我正在使用 NSFetchedResultsControllerUITableViewController 从 CoreData 数据库填充 UITableView。

我有一个NSDate 对象保存到这个标记为“startTime”的日期属性中。然后我尝试使用如下所示的NSPredicate 仅提取今天的数据:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startDate == %@",
                          todaysDate];

我得到的结果为零。我理解这一点,因为 NSDate 对象只保存自 1970 年 1 月 1 日以来的秒数或毫秒数,对吗?所以比较 1111111111111 和 1111111111112,而在同一天,是两个不同的 NSDate 不相等的对象。

那么,如何格式化NSPredicate 以便它能够做到这一点?我猜它会创建两个 NSDate 对象:一个是昨晚凌晨 12 点,另一个是今晚凌晨 12 点,然后比较 startDate 看看它是否在这两个 NSDates 之间。

我对@9​​87654331@ 有点陌生,那么如何实现呢?

【问题讨论】:

  • 您应该将解决方案放在答案中,而不是将其放在问题中。
  • 不能@yuji,因为我还没有足够的代表。
  • 也许您可以将您的解决方案放入答案中。同时,我已将其编辑掉,因为您已经接受了 yuji 的回答。您可以通过查看修订历史来恢复您的解决方案。谢谢。

标签: core-data nsdate uitableview nspredicate nsfetchedresultscontroller


【解决方案1】:

使用NSCompoundPredicate

NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"startDate > %@", firstDate];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"startDate < %@", secondDate];

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]];

firstDate 是今天早上 12 点,secondDate 是今晚 12 点。

附:今天早上 12 点的方法如下:

NSCalendar *calendar = [NSCalendar calendar]; // gets default calendar
NSCalendarComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, and day for today's date
NSDate *firstDate = [calendar dateFromComponents:components]; // makes a new NSDate keeping only the year, month, and day

要到今晚 12 点,请更改 components.day

【讨论】:

  • 非常感谢 - 几个小错别字 - andPredicateWithSubpredicates(小写 P)并使用 NSDateComponents 而不是 NSCalendarComponents
猜你喜欢
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
相关资源
最近更新 更多