Find it on GitHub.

A simple, non-intrusive library for recursively serializing CoreData object-graphs to JSON and property lists.

Installation

CDSerialization is provided as a module (introduced in iOS 8), so installation is as simple as adding this project as a dependency, linking the product framework and adding a “Copy Files” build phase to copy over the framework to be linked at runtime.

Usage

CDSerialization provides a serialization and a deserialization context for each operation. It’s important to note that after the object graph has been serialized or deserialized once, all objects will be cached for the lifetime of the respective context. Future calls to serialize or deserialize will be virtually *free*. Only new objects added will incur any cost.

Serialization

To serialize an object graph, we’ll need to instantiate a CDSerializationContext, add some objects, and perform the work.

Deserialization

To deserialize an object graph, we’ll need to instantiate a CDDeserializationContext and pass in a valid NSManagedObjectContext. The managed object context will act as a container for all objects created during the deserialization process.

Deserialization will return an NSSet of all deserialized objects of type NSManagedObject. It is not necessary to do anything further with this set.

Result

So what’s the result? Essentially, what you’ll get after serializing a CoreData object graph is a dictionary with two keys for:

  1. Top level objects
  2. Object references

CDSerializationTopReferences represents the objects added directly to the context and are simply a pointer into the global object table. CDSerializationReferences provides the global object table and includes all objects that are recursively derived from the top level object fed into the context.

Delegates

Both contexts provide a way for delegates to be part of the serialization & deserialization process. Assigning a delegate to a context grants delegates the ability to respond to will and did serialize / deserialize events.

Limitations

  • as of right now, it’s an all or nothing deal, which means that you can’t serialize individual objects in isolation, unless the object has no relationships.
  • no way to prevent duplicate imports, monitor the process of inserting deserialized objects into the managed object context

The limitations above will likely be addressed some time in the future.