O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

18.10. Using Custom Data Types in Your Core Data Model

Problem

You believe the choice of data types provided by Core Data doesn’t suit your needs. You may need to use more data types, such as UIColor, in your model objects, but Core Data doesn’t offer that data type out of the box.

Solution

Use transformable data types.

Discussion

Core Data allows you to create properties on your model objects and assign data types to those properties. Your choice is quite limited: a data type can be used in Core Data only if it can be turned into an instance of NSData and back again. By default, there are a number of popular classes, such as UIColor, that you cannot use for your properties. So what is the way around it? The answer is transformable properties. Let me explain the concept to you first.

So let’s say that we want to create a model object in Core Data and name that model object Laptop. This object is going to have two properties: a model of type String and a color that we want to be of type UIColor. Core Data does not offer that data type, so we have to create a subclass of the NSValueTransformer class. Let’s name our class ColorTransformer. Here are the things you have to do in the implementation of your class:

  1. Override the allowsReverseTransformation class method of your class and return YES from it. This will tell Core Data that you can turn colors into data and data back into colors.

  2. Override the transformedValueClass class method of your class and return the class name of NSData from it. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required