Serializing Data – domain model to persistence

http://nshipster.com/nscoding/

There are many ways you serialize data, or convert domain model to persistence:

Core Data
NSKeyedArchiver
pList
NSUserDefault
etc…

Core Data may not be your answer because:

Not all apps need to query data.
Not all apps need automatic migrations.
Not all apps work with large or complex object graphs.

NSKeyArchiver and NSCoding

Thus, using NSKeyArchiver and NSCoding maybe a great solution in some cases.

NSCoding is a simple protocol, with two methods: -initWithCoder: and encodeWithCoder:. Classes that conform to NSCoding can be serialized and deserialized into data that can be either be archived to disk or distributed across a network.

NSKeyArchiver serializes -compliant classes to and from a data representation.

NSCoding delegates

This is so that you can tell it what properties to encode into objects. Encode means to “convert into a coded form”.
Hence, we inject our properties into encodeObject.

Decode means to convert a coded message into something readable.
Thus, that’s why we have our properties take on data returned by the decoder.

Each property is encoded or decoded as an object or type, using the name of the property of as the key each time.

File System

NSKeyedArchiver and NSKeyedUnarchiver provide a convenient API to read / write objects directly to / from disk.

You first get the path of the directory you want. Then you append a file name to that path. The resulting NSString appFile is your full path to the file you are saving to.

Then, use your Array or Dictionary, and insert it into NSKeyedArchiver’s archiveRootObject toFile method in order to save.
When you want to load, use unarchiveObjectWithFile:appFile.

pLists

A property list (a.k.a. pList) is a structured data representation used by Cocoa and Core Foundation as a convenient way to store, organize, and access standard types of data. You can build little more complex structures but not that much. NSString, NSData, NSNumber, NSDate, NSArray, NSDictionary – these are the only Objective-C data types that property list supports. Sub-entries are only allowed with NSDictionary or NSArray. A property list is used to store “less than a few hundred kilobytes” of data. A very significant and popular use of property lists is to define application settings.

If you open a pList with Xcode this is how it will show a very comfortable view of key-value pairs. But if you open the pList with a text editor you will see the actual format, which is XML. Property list is a subset of XML.