我在持久性存储中以以下格式存储了一个称为NSDate
的startDate
属性,如下所示(下图)。
426174354 = 2014年7月4日
我需要使用谓词创建(3)NSFetchRequest
。
对于startDate
:
使用谓词的
fetchRequest1
需要根据用户的设备时间来获取当前日期中的所有内容。 fetchRequest2
需要根据用户的设备时间来获取过去(即昨天和之前)的所有内容。 fetchRequest3
需要获取 future 的所有内容,这意味着根据用户的设备时间从明天开始。 下面是我到目前为止的代码:
-(NSMutableArray *)getFetchPredicate:(NSUInteger)fetchRequestType
{
NSDate *now = [self getcurrentTime:[NSDate date]];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = @"dd-MM-yyyy";
format.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSString *stringDate = [format stringFromDate:now];
NSDate *todaysDate = [format dateFromString:stringDate];
//today's date is now a date without time.
NSMutableArray *subpredicates;
if (fetchRequestType == 1)
{
NSPredicate *subPredToday = [NSPredicate predicateWithFormat:@"startDate == %@ ", todaysDate];
[subpredicates addObject:subPredToday];
}
else if (fetchRequestType == 2)
{
NSPredicate *subPredPast = [NSPredicate predicateWithFormat:@"startDate < %@", todaysDate];
[subpredicates addObject:subPredPast];
}
else if (fetchRequestType == 3)
{
NSPredicate *subPredFuture = [NSPredicate predicateWithFormat:@"startDate > %@", todaysDate];
[subpredicates addObject:subPredFuture];
}
return subPredicates;
}
-(NSDate *)getcurrentTime:(NSDate*)date
{
NSDate *sourceDate = date;
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* deviceDateWithTime = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
return deviceDateWithTime;
}
上面的代码没有从CoreData获取正确的对象。我感到我的比较谓词不正确。我不确定如何将
startDate
中存储的时间仅转换为仅Date格式,并将其应用于谓词进行比较。有什么建议么? 最佳答案
我认为todaysDate
的概念出了问题。 AFAIK的NSDate
表示绝对时间点,因此您创建不带“时间”的“日期”的努力似乎是徒劳的。而且使用NSDateFormatter
设置日期也很不稳定。
我认为您必须创建两个不同的NSDate
对象:startOfCurrentDay
(例如00:00:00)和endOfCurrentDay
(例如23:59:59),就我个人而言,我可以通过使用NSCalendar
来实现。如果这样做,则您的提取请求谓词将为:
if (fetchRequestType == 1)
{
NSPredicate *subPredToday = [NSPredicate predicateWithFormat:@"(startDate >= %@) AND (startDate <= %@)", startOfCurrentDay, endOfCurrentDay];
}
else if (fetchRequestType == 2)
{
NSPredicate *subPredPast = [NSPredicate predicateWithFormat:@"startDate < %@", startOfCurrentDay];
}
else if (fetchRequestType == 3)
{
NSPredicate *subPredFuture = [NSPredicate predicateWithFormat:@"startDate > %@", endOfCurrentDay];
}
关于iOS:使用NSDate进行比较的NSPredicate,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24534311/