简体   繁体   English

如何保存NSDate的状态并将其加载到文件中?

[英]How can I save and load the state of a NSDate to a file?

I would like my app to load in the state of a NSDate object when is loaded and be able to save a new state set by a spinner. 我希望我的应用在加载时以NSDate对象的状态加载,并能够保存微调器设置的新状态。

My first dea was to get the NSdate object from the spinner then call descriptionWithLocale to get the date as a string, then save this string. 我的第一个方法是从微调器中获取NSdate对象,然后调用descriptionWithLocale将日期作为字符串获取,然后将其保存。 But I could not see any methods to load a date as a string into a NSDAte. 但是我看不到任何将日期作为字符串加载到NSDAte中的方法。

Depending on your requirements, you have a couple of options. 根据您的要求,您有两种选择。 As Carl and rmaddy pointed out, NSDate conforms to NSCoding, which means it is serializable and can be easily stored in the NSUserDefaults. 正如Carl和rmaddy所指出的那样,NSDate符合NSCoding,这意味着它可以序列化,并且可以轻松地存储在NSUserDefaults中。 Here's a nice tutorial on using NSUserDefaults. 这是有关使用NSUserDefaults的不错的教程

Alternatively, you can just store the date as an NSTimeInterval. 或者,您可以仅将日期存储为NSTimeInterval。 In that case, you can use any of the following methods to store and retrieve the NSDate object (from NSDate class reference ). 在这种情况下,可以使用以下任何一种方法来存储和检索NSDate对象(来自NSDate类参考 )。

+ dateWithTimeIntervalSinceReferenceDate:
+ dateWithTimeIntervalSince1970:
– timeIntervalSinceReferenceDate
– timeIntervalSince1970

The dateWithTimeIntervalSince1970 and corresponding timeIntervalSince1970 methods are useful if you care about storing the date in epoch time. 如果您关心将日期存储在纪元时间中,则dateWithTimeIntervalSince1970和相应的timeIntervalSince1970方法将很有用。

Instead of converting NSData to NSString , better way is convert to NSTimeInterval (which is double ) using NSDate -timeIntervalSince1970 method, then you can sore it in NSUserDefaults if you like. 除了将NSData转换为NSString ,更好的方法是使用NSDate -timeIntervalSince1970方法转换为NSTimeInterval(这是double ),然后可以根据需要在NSUserDefaults中对其进行处理。

If you really want save to file you can insert NSDate into NSDictionary object then save NSDictionary with -writeToFile:atomically: method (restore with +dictionaryWithContentsOfFile: ) 如果您确实要保存到文件,则可以将NSDate插入NSDictionary对象,然后使用-writeToFile:atomically:方法保存NSDictionary (使用+dictionaryWithContentsOfFile:恢复)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM