我有一个NSDate,我将其存入NSUserDefaults。
当我的应用程序运行此代码进行第二次传递时,我希望从NSUserDefaults中检索NSDate,但它总是为零。不知道为什么。
NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp];
NSDate *savedMentionDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"mostRecentMentionDate"];
if (savedMentionDate == nil || [savedMentionDate isEqual:[NSNull null]]) {
//There is no existing mention, so save the most recent one
[[NSUserDefaults standardUserDefaults]setObject:mostRecentMentionDate forKey:@"mostRecentMentionDate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
答案 0 :(得分:1)
如果我使用此代码,它可以正常工作,我认为你的dateformater问题
NSDate *mostRecentMentionDate = [NSDate date];
NSDate *savedMentionDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"mostRecentMentionDate"];
if (savedMentionDate == nil || [savedMentionDate isEqual:[NSNull null]]) {
//There is no existing mention, so save the most recent one
[[NSUserDefaults standardUserDefaults]setObject:mostRecentMentionDate forKey:@"mostRecentMentionDate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
答案 1 :(得分:1)
您确定要获得mostRecentMentionDate
的有效对象吗?在从NSUserDefaults获取savedMentionDate
之前将其放入NSLog,您可能遇到日期格式问题。
答案 2 :(得分:0)
NSDate确认NSCoding协议。上面的代码应该工作。
试试这个 -
/
/ Create and store it
NSDate * date = [NSDate date];
NSData * dateData = [NSKeyedArchiver archivedDataWithRootObject:date];
[dateData writeToFile:@"/Some/path/to/file.dat" atomically:NO];
// Now bring it back
NSData * restoredDateData = [NSData dataWithContentsOfFile:@"/Some/path/to/file.dat"];
NSDate * restoredDate = [NSKeyedUnarchiver unarchiveObjectWithData:restoredDateData];
或者您可以将timeIntervalSinceReferenceDate值作为NSNumber(double)并将其保存到NSUserDefault
以跟踪上一个日期。