我从iCloud获取数据,如果它比设备上的数据更新,我想比较它。但是,即使iCloud数据较旧,我的if语句也会计算为true。
这是我的代码:
NSLog(@"users date: %@",userDefaultsModificationDate);
NSLog(@"icloud fetch date : %@",fetchedRemindersRecord.modificationDate);
NSComparisonResult result = [[NSCalendar currentCalendar] compareDate:fetchedRemindersRecord.modificationDate toDate:userDefaultsModificationDate toUnitGranularity:NSCalendarUnitSecond];
switch (result) {
case NSOrderedSame:
NSLog(@"same");
break;
case NSOrderedDescending:
NSLog(@"desc");
break;
case NSOrderedAscending:
NSLog(@"asc");
break;
default:
break;
}
if (result == NSOrderedDescending){
[self createReminders:[NSKeyedUnarchiver unarchiveObjectWithData:[fetchedRemindersRecord objectForKey:@"reminders"]]];
NSLog(@"Fetched records successfully users date: %@",userDefaultsModificationDate);
NSLog(@"Fetched records successfully icloud fetch date : %@",fetchedRemindersRecord.modificationDate);
}
控制台:
users date: 2016-08-28 22:52:05 +0000
icloud fetch date : 2016-08-28 22:51:57 +0000
asc
Fetched records successfully users date: 2016-08-28 22:44:16 +0000
Fetched records successfully icloud fetch date : 2016-08-28 22:43:38 +0000
正如您可以清楚地看到的那样,iCloud数据较旧,并且switch语句表示订单是升序的,但if语句仍然评估为true。我甚至检查过以确保在比较之前两个日期都不是nil
。
我一直在努力奋斗一个小时,似乎无法弄清楚发生了什么......可能是我忽略的一些显而易见的事情。
提前致谢!
编辑:无论我将result
与之比较,它总是评估为真
答案 0 :(得分:0)
当我运行此代码时:
NSDateFormatter* df = [NSDateFormatter new];
df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate* date1 = [df dateFromString:@"2016-08-28 22:52:05"];
NSDate* date2 = [df dateFromString:@"2016-08-28 22:51:57"];
NSLog(@"users date: %@", date1);
NSLog(@"icloud fetch date : %@", date2);
NSComparisonResult result = [[NSCalendar currentCalendar] compareDate:date2 toDate:date1 toUnitGranularity:NSCalendarUnitSecond];
switch (result) {
case NSOrderedSame:
NSLog(@"same");
break;
case NSOrderedDescending:
NSLog(@"desc");
break;
case NSOrderedAscending:
NSLog(@"asc");
break;
default:
break;
}
if (result == NSOrderedSame){
NSLog(@"same 2");
}
if (result == NSOrderedDescending){
NSLog(@"desc 2");
}
if (result == NSOrderedAscending){
NSLog(@"asc 2");
}
我得到了这个结果:
2016-08-29 09:25:22.737 Junk6[34957:1961720] users date: 2016-08-28 12:52:05 +0000
2016-08-29 09:25:22.738 Junk6[34957:1961720] icloud fetch date : 2016-08-28 12:51:57 +0000
2016-08-29 09:25:22.738 Junk6[34957:1961720] asc
2016-08-29 09:25:22.739 Junk6[34957:1961720] asc 2
我无法运行您的代码,除非您发布整个项目或显示问题的简化示例。