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:
Override the
allowsReverseTransformationclass method of your class and returnYESfrom it. This will tell Core Data that you can turn colors into data and data back into colors.Override the
transformedValueClassclass method of your class and return the class name ofNSDatafrom it. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access