CoreData with Codable

Deepika Ramesh
2 min readJan 10, 2022

--

Populating & persisting managed objects by parsing the JSON data with codable!

Prerequisites:

Some knowledge of CoreData and be able to set up a simple CoreData project

Terminology

  • CoreData: A framework that allows you to manage the model layer objects in your application. CoreData does this by being an object graph management and persistence framework.
  • Codable: It is a union of two protocols Encodable & Decodable, it helps to encode and decode data to/from a serialized format

The idea is to parse JSON data and save it directly into CoreData.

NSManagedObject + Codable:

We need to implement Encodable’s encode(to:) and Decodable’s init(from:) appropriately. Simple right! but it is not actually as it sounds. In this article, we’ll focus on only decoding the data.

The main problem is we need to have the information about managed object context in which the managed object needs to be created.

We can’t change the signature of the init and explicitly pass the required managed object context as a parameter, we have to find an alternative way to make the context available.

One way to achieve that is to store the context in the userInfo dictionary, which is a property of the Decoder instance. The userInfo requires a key of CodingUserInfoKey type to store the information.

Now, we can easily access the context from the userInfo of the decoder with CodingUserInfoKey.context. But this is an optional value, so instead of crashing we can throw an error and let the consumer decide how to handle it, like this:

Parsing JSON data & storing it in CoreData:

Before parsing the data we shall create a convenience init to JSONDecoderm which accepts the context and insert it into the userInfo dictionary:

With the help of the above init let's parse the JSON data and create the managed object for the type we want. We’ll add this function as an extension to Decodable where Self is NSManagedObject.

Now let's create a model which can be inited by parsing JSON data with codable in the decoder init we’ll be accessing the context as explained above and initialize the NSManagedObject.

Now with all these setups done, its time to persist the data

Conclusion:

In this post, we saw how to parse JSON data and store them in CoreData using the Codable protocol step by step.

--

--