我遇到了一个问题,我将NSUserDefault密钥设置为我的" currentDate"但它的值似乎是4秒后,然后是存储在CoreData中的值。我正在使用相同的' currentDate' NSDate值如下面的代码所示。我认为这是因为它在保存NSUserDefaults后4秒又重新获取了日期选择器的当前日期?我该如何解决这个问题?
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
EventEntry *entry = [NSEntityDescription insertNewObjectForEntityForName:@"EventEntry" inManagedObjectContext:coreDataStack.managedObjectContext];
entry.title = self.titleField.text;
entry.date = self.datePicker.date.timeIntervalSinceNow;
[coreDataStack saveContext];
//Create the dateformatter object
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
//Set the required date format
[formatter setDateFormat:@"yyyy-MM-dd HH:mm a"];
NSCalendar *calender = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currentDate = self.datePicker.date;
NSLog(@"Todays date is %@",[formatter stringFromDate:currentDate]);
NSDateComponents *dateComp = [NSDateComponents new];
notificationTime = -notificationTime;
[dateComp setMinute:notificationTime];
[dateComp setSecond:0];
NSDate *targetDate = [calender dateByAddingComponents:dateComp toDate:currentDate options:0];
NSLog(@"Local Notification is set for %@",[formatter stringFromDate:targetDate]);
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = targetDate;
localNotification.alertBody = @"Testing Local Notification";
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *dateString = [formatter stringFromDate:currentDate];
NSLog(@"Date String Key: %@", dateString);
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:localNotification];
[userDefaults setObject:data forKey:dateString];
[userDefaults synchronize];
答案 0 :(得分:0)
您没有对托管对象和用户默认密钥使用相同的日期。
相反,您应该使用currentDate
。
entry.date = currentDate;