本文介绍了在 NSUserDefaults 中存储 NSDate 的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过两种在 NSUserDefaults 中存储 NSDate 的方法.

There's two ways of storing an NSDate in NSUserDefaults that I've come across.

// Set
NSDate *myDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:myDate forKey:@"myDateKey"];

// Get
NSDate *myDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"myDateKey"];

选项 2 - timeIntervalSince1970

// Set
NSDate *myDate = [NSDate date];
NSTimeInterval myDateTimeInterval = [myDate timeIntervalSince1970];
[[NSUserDefaults standardUserDefaults] setFloat:myDateTimeInterval forKey:@"myDateKey"];

// Get
NSTimeInterval myDateTimeInterval = [[NSUserDefaults standardUserDefaults] floatForKey:@"myDateKey"];
NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:myDateTimeInterval];

优点和缺点

选项 1

这似乎是紧凑和合乎逻辑的.但是,由于日期格式化程序错误.

This seems to be compact and logical. However, I've got worries about this going wrong because of Date Formatter bugs.

选项 2

这似乎很笨拙.我也不确定它的准确性 - 在我做过的一项测试中,当我检索日期时,它已经过期 48 秒,尽管 Apple Docs 说 NSTimeInterval 具有亚秒级精度".

This seems to be clumsy. I'm also unsure of the accuracy of it - in one test I did, when I retrieved the date back it was out by 48 seconds, despite the Apple Docs saying that NSTimeInterval has "subsecond accuracy".

无论我选择哪种方法,它都必须是:

Whatever method I choose, it must be:

  1. 精确到一秒.

  1. Precise to within a second.

可读且可靠.

我的问题

选项 2 的不准确是因为我做错了什么吗?

My Question

Is the inaccuracy with Option 2 because I'm doing something wrong?

您会使用这两个选项中的哪个?

Which out of these two options would you use?

还有其他我不知道的选择吗?

Is there another option that I'm not aware of?

谢谢!

推荐答案

你把事情不必要地复杂化了.为什么要将日期转换为时间间隔(然后将时间间隔转换为不同的原语)?只需 [sharedDefaults setObject:theDate forKey:@"theDateKey"] 并完成它.NSDate 是PLIST 格式(日期、数字、字符串、数据、字典和数组)支持的主要类型"之一,因此您可以直接存储它.

You are needlessly complicating things. Why are you converting the date to a time interval (then the time interval to a different primitive)? Just [sharedDefaults setObject:theDate forKey:@"theDateKey"] and be done with it. NSDate is one of the "main types" supported by the PLIST format (dates, numbers, strings, data, dictionaries, and arrays), so you can just store it directly.

参见 文档 证明.

直接存储和检索日期并观察它做正确的事(包括时区、精度等).正如其他人所说,不涉及格式化程序.

Just store and retrieve the date directly and watch it Do The Right Thing (including time zones, precision, etc). There is no formatter involved, as others have said.

这篇关于在 NSUserDefaults 中存储 NSDate 的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:28
查看更多