我无法弄清楚这里发生了什么......基本上,我的代码保存了一个对象(到服务器)并在NSUserDefaults中记录时间。下次用户尝试保存对象时,我会检查日期是否在存储时间和存储时间加上2小时之间。所以基本上,我想阻止用户在另一个对象的2小时内保存一个额外的对象。我已经编写并完成了代码......这是捕获,它在我的结束时(中央标准时间)100%的时间工作,但我在加利福尼亚州(太平洋时间)有一个beta测试人员,它有问题。记录的时间是正确的,但2小时的窗口是关闭的,通常不会被覆盖...在应用程序中有一些其他地方可以更新时间,但代码基本上,完全相同。 / p>
以下是“保存对象方法”中的代码:
//Combine date and time
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components1 = [gregorianCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:self.pickedDate];
NSDateComponents *components2 = [gregorianCalendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:self.pickedTime];
NSDateComponents *components3 = [[NSDateComponents alloc] init];
[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];
[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
[components3 setSecond:components2.second];
//Generate a new NSDate from components3.
NSDate *combinedDate = [gregorianCalendar dateFromComponents:components3];
//Create "plus 2 hour" date
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate *time = [defaults objectForKey:@"lastObject_time"];
NSTimeInterval twoHours = 2 * 3600;
NSDate *plusTwoHours = [time dateByAddingTimeInterval:twoHours];
if (time) {
//There is a stored time
if (![self date:combinedDate isBetweenDate:time andDate:plusTwoHours]) {
//After 2 hours, allow save. After save, check if it's the LATEST date, compared to what we have stored
if ([combinedDate compare:[defaults objectForKey:@"lastObject_time"]] == NSOrderedDescending) {
//Save as most recent time
[defaults setObject:combinedDate forKey:@"lastObject_time"];
[defaults synchronize];
}
} else {
//Before 2 hours, prevent save
}
} else {
//No stored time, allow save
}
这是我的isBetweenDate
方法
-(BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate {
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endDate] == NSOrderedDescending)
return NO;
return YES;
}
就像我说的,时间是根据他们的时区存储的,我不认为这是时区问题。我的beta测试仪在上午7点有几次保存(存储时间是早上7点,阻塞到上午9点),然后在下午12点保存(这是允许的),但随后范围不会更新到12-2 PM ,并且在上午7点到9点被困住了,然后他们被允许在下午12:01再次保存。有没有理由说它不能跨时区工作?有没有人看到任何跳出来的东西?有类似的经历吗?或者有更好的方法吗?