我有一个名为startDate的NSDate属性存储在持久性存储中,格式如下(下图).
426174354 = 2014年7月4日
我需要使用谓词创建(3)NSFetchRequest.
对于startDate:
> fetchRequest1使用谓词需要根据用户的设备时间获取今天日期中的所有内容.
使用谓词的fetchRequest2需要根据用户的设备时间来获取过去的所有内容,这意味着昨天和之前的内容.
使用谓词的fetchRequest3需要获取将来的所有内容,这意味着基于用户设备时间的明天和之后的开始.
以下是我到目前为止的代码:
-(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中的存储时间转换为仅日期格式,并将其应用于Predicates进行比较.有什么建议么?
解决方法
我认为你今天的看法有问题. 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];
}