Best practice? – Array/Dictionary as a Core Data Entity Attribute [closed]

There is no “native” array or dictionary type in Core Data. You can store an NSArray or an NSDictionary as a transformable attribute. This will use the NSCoding to serialize the array or dictionary to an NSData attribute (and appropriately deserialize it upon access). The advantage of this approach is that it’s easy. The downside is that you can’t query into the array or dictionary (it’s stored as a BLOB in the data store) and if the collections are large, you may have to move a lot of data to/from the data store (if it’s an SQLite data store) just to read or modify a small part of the collection.

The alternative is to use Core Data to-many relationships to model the semantics of the array or dictionary collection. Arrays are easier, so lets start with that. Core Data to-many relationships are really modelling a set, so if you need array-like functionality, you have to either sort the set (using a fetched property is a convenient way to do this) or add an extra index attribute to the entity that stores the array items and manage the indexes yourself. If you are storing a homogeneous array (all entries are the same type), it’s easy to model the entity description for the array entities. If not, you’ll have to decide whether to use a transformable attribute to store the item data or create a family of item entities.

Modeling a dictionary will likely require a to-many relationship to a set of entities that stores a key and a value. Both key and value are analogous to the item entity for the array, described above. So they could either be native types (if you know them ahead of time), a transformable attribute or a relationship to an instance from a family of type-specific entities.

If this all sounds a bit daunting, it is. Shoehorning arbitrary data into a schema-dependent framework like Core Data is tough.

For structured data, like addresses, it’s almost always easier to spend the time modeling the entities explicitly (e.g. an attribute for each part of the address). Besides avoiding all the extra code to model a dictionary, this makes your UI easier (bindings will “just work”) and your validation logic etc. much clearer since much of it can be handled by Core Data.


As of OS X 10.7, Core Data includes an ordered set type which can be used in place of an array. If you can target 10.7 or later, this is the best solution for ordered (array-like) collections.

Leave a Comment