Search code examples
iosobjective-ccore-data

Example of Custom Class on the Transformable property of Core Data


When you create a Transformable property on core data, you generally add the NSValueTransformer code to the entity's class and fill its name on the Value Transformer field of the data model inspector, but what about the Custom Class field? What is the purpose of that field? Can you give a simple example?

enter image description here


Solution

  • "Custom Class" controls what happens to this property when Xcode generates subclasses of / extensions on NSManagedObject. If you leave this field blank, your snapshot field will be declared as an NSObject. If you fill in a class name, Xcode will declare the attribute as whatever class name you enter.

    In practice that means that if you make snapshot transformable, leave that field blank, and then Xcode generates a subclass for you, the property will be declared as:

    @NSManaged public var snapshot: NSObject?
    

    On the other hand if you fill in that field, for example by typing UIImage there, then when Xcode generates the subclass the property will be declared as:

    @NSManaged public var snapshot: UIImage?
    

    Filling in a class name allows the compiler to check your assignments so that if, for example, the property is a UIImage, you don't mistakenly try to assign an NSData to it.

    Update: If you're using Swift, you also need to add a value for the "module" field in the property configuration, just below "custom class". For the snapshot property here, do this:

    Core Data transformable property with custom class set to UIImage and module set to UIKit

    When you do this, the generated source code will include import UIKit so that the code will compile. Thanks to @grego for pointing this out in a comment.