我正在使用一个NSFetchedResultsController
and a 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
,那么如何才能实现这一点呢?
Use NSCompoundPredicate
.
NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"startDate > %@", firstDate];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"startDate < %@", secondDate];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]];
Where 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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)