Okay, so we've stored a number of data types in UserDefaults, and we've saved textual data to the user's Documents folder. How do we save our own custom objects to the file system?
We need to make our custom objects conform to the NSCoding protocol. This means, firstly, that the object in question knows how to serialize itself (or, at least, tell the system to serialize itself), and secondly, that it provides an interface to the code outside the object, through which we can instruct the object to encode and decode data.
NSCoding is a very simple protocol; it requires two methods:
- initWithCoder
- encodeWithCoder
Objects that conform to NSCoding can then be serialized and de-serialized into data that can be saved to disk (or, indeed, sent across a network). So, we have three tasks to complete:
- Create an NSCoding--compliant class
- Write a save-to-disk method
- Write a load-from...