How to persist and load an object which conforms to NSCoding protocol?
-
20-09-2019 - |
Question
I have made an class which conforms to the NSCoding protocol and does all the encode and decode stuff.
For my app, I simply want to persist an object from that class to the device and the next time when the app launches, I want to load that object back into memory.
Basically it's just an class which holds some user input information. For example the user starts writing a text but then quits the app. Next time I want to load that data object.
I guess I need NSKeyedArchiver? Is there a good tutorial on this? How do I do that?
Solution
Yes you need NSKeyed(Un)Archiver. These 2 classes can convert your object to/from NSData which you can save/load it as a file.
To save your object to a file:
if (![NSKeyedArchiver archiveRootObject:your_object toFile:@"filename.plist"])
// save failed.
To read the object from a file:
id your_object = [NSKeyedUnarchiver unarchiveObjectWithFile:@"filename.plist"];
if (your_object == nil)
// read failed.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow