简体   繁体   中英

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.

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. But I could not see any methods to load a date as a string into a 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. Here's a nice tutorial on using NSUserDefaults.

Alternatively, you can just store the date as an NSTimeInterval. In that case, you can use any of the following methods to store and retrieve the NSDate object (from NSDate class reference ).

+ dateWithTimeIntervalSinceReferenceDate:
+ dateWithTimeIntervalSince1970:
– timeIntervalSinceReferenceDate
– timeIntervalSince1970

The dateWithTimeIntervalSince1970 and corresponding timeIntervalSince1970 methods are useful if you care about storing the date in epoch time.

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.

If you really want save to file you can insert NSDate into NSDictionary object then save NSDictionary with -writeToFile:atomically: method (restore with +dictionaryWithContentsOfFile: )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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