Reading and writing NSArray into Core Data with Transformable types

Core Data is great, but coming to grips with it can be a bit of a headache for first time users. Out of the box, iOS allows you to declare model properties with a variety of types: String, Float, Date, Boolean, Int 16/32/64, but annoyingly, not arrays. Enter Transformable types.

With Transformable types, you can store anything as NSData and load it back to a format that’s useable for you. This includes, NSArrays.

This brief post assumes you already know how to get setup with Core Data, and how to create an NSManagedObject subclass of your own Entity.

Take the example below:

Above, we create a new Car entity which has an attribute named “wheels” of the Transformable type. We set this attribute to be the wheelsArray we declared earlier, and save.

How do we get this data back? All we do is initialise a new NSArray with the contents of car.wheels and we’re good to go. In a real application, we would have more code in place to perform various checks and error handling, but this should give you a good idea of what’s required:

Leave a comment