使用Core Data与NSPredicate和NSDate [英] Using Core Data with NSPredicate and NSDate
问题描述
我有一个事件
表保存 NSString *操作
和 NSDate * date
。我要过滤从核心数据检索的数组,以显示在最后一小时和下一小时执行的所有操作,而不取决于保存的日期。星期二的示例示例在16:00时保存,但今天是星期五17:00,我仍然希望检索周二保存的操作以及该时间范围内的任何操作。
I have a Event
table that saves a NSString *action
and a NSDate *date
. I want to filter the array retrieved from core data to display all the actions performed in the last hour and the next hour not depending on the day it was saved. Example on Tuesday a action was saved on 16:00 but Today is Friday 17:00 and I still want to retrieve that action saved on Tuesday and any action within that time frame.
推荐答案
任何人遇到这个问题。更改我的事件表以保持整数(小时的操作),并检索它像这样
For anyone stuck with this problem. Changed my Event Table to hold a integer (hour of the action) and retrieved it like this
NSDate *currentFullDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:currentFullDate];
NSInteger currentHour = [components hour];
NSInteger hourAgo = currentHour -1;
NSInteger nextHour = currentHour +1;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
request.predicate = [NSPredicate predicateWithFormat:@"(hour >=%@) AND (hour <= %@)", hourAgo, nextHour];
request.fetchLimit = 5;
NSError *error;
NSArray *eventArray = [managedObjectContext executeFetchRequest:request error:&error];
for (Event *event in eventArray)
{
}
这篇关于使用Core Data与NSPredicate和NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!