我正在使用NSFetchedResultsController
和UITableViewController
从CoreData数据库填充UITableView。
我有一个NSDate
对象保存在标记为“startTime”的Date属性中。然后我试图通过使用看起来像这样的NSPredicate
来获取今天的数据:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startDate == %@",
todaysDate];
我的结果为零。我理解这一点是因为一个NSDate
对象只保留了自1970年1月1日以来的秒数或毫秒数等等吗?因此,比较1111111111111和1111111111112,而在同一天,两个不同的NSDate
对象不相等。
那么,如何对NSPredicate
进行格式化以便它能够实现呢?我猜它会创建两个NSDate
对象:一个是昨晚12点,另一个是今晚12点,并比较startDate,看看它是否在这两个NSDate
之间。
我是NSPredicate
的新手,所以怎么能实现呢?
答案 0 :(得分:24)
使用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点。
P.S。以下是今天早上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
。