2014-12-02 52 views
0

我遇到了一個問題,我將一個NSUserDefault鍵設置爲「currentDate」,但它的值似乎是4秒後,然後是存儲在CoreData中的值。我使用下面的代碼中看到的'currentDate'NSDate值。我認爲這是因爲當它保存NSUserDefaults時,它在4秒之後再次抓取日期選擇器當前日期?我將如何解決這個問題?在NSDefaults中使用NSDate作爲唯一標識符

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

您沒有對您的託管對象和用戶默認密鑰使用相同的日期。您可以使用currentDate

entry.date = currentDate; 
+0

entry.date是一個NSTimeInterval這就是爲什麼它的轉換,但是我甚至試圖移動的NSDate *的currentdate = self.datePicker.date;上面的entry.date = currentDate;並將其更改爲entry.date = currentDate.timeIntervalSinceNow;仍然沒有運氣。 – Joey 2014-12-02 19:37:37

+0

你爲什麼不把日期保存爲日期?由於可移動目標「現在」以後的選擇日期和時間間隔,您有兩個數據點,其中一個是不必要的。 – Mundi 2014-12-02 20:28:23