【问题标题】:Using NSDate as Unique Identifier in NSDefaults在 NSDefaults 中使用 NSDate 作为唯一标识符
【发布时间】:2014-12-02 19:13:45
【问题描述】:

我遇到了一个问题,我将 NSUserDefault 键设置为我的“currentDate”,但它的值似乎比存储在 CoreData 中的值晚 4 秒。我正在使用与下面代码中相同的“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];

【问题讨论】:

    标签: objective-c core-data nsuserdefaults


    【解决方案1】:

    您的托管对象和用户默认密钥没有使用相同的日期。

    您应该使用currentDate

    entry.date = currentDate;
    

    【讨论】:

    • entry.date 是一个 NSTimeInterval 这就是它被转换的原因,但是我什至尝试移动 NSDate *currentDate = self.datePicker.date;以上 entry.date = currentDate;并将其更改为 entry.date = currentDate.timeIntervalSinceNow;仍然没有运气。
    • 为什么不将日期保存为日期?使用选择器日期和自可移动目标“现在”以来的时间间隔,您有两个数据点,其中一个是不必要的。
    猜你喜欢
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2016-02-18
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多