Storing UIColor object in Core Data

Your attribute should be of the type Transformable. The default value transformer (NSKeyedUnarchiveFromDataTransformerName) can transform any object that conforms to NSCoding.

  1. Mark the attribute as type "Tranformable".
  2. Optional: Set the Value Transformer Name to "NSKeyedUnarchiveFromDataTransformerName". If you do not, it will default to this anyway.

Like so

You do not have to do anything else. Keep in mind you will not be able to match transformable attribute with a predicate or sort by them. They are pretty much just storage - the value transformer transforms the object value into NSData, which is what gets persisted in the store. When the attribute fault fires Core Data uses the transformer in the other direction to go from NSData to your object type.


Another option available, Swift 3

extension UIColor {
    class func color(withData data:Data) -> UIColor {
         return NSKeyedUnarchiver.unarchiveObject(with: data) as! UIColor
    }

    func encode() -> Data {
         return NSKeyedArchiver.archivedData(withRootObject: self)
    }
}

Usage

var myColor = UIColor.green
// Encoding the color to data
let myColorData = myColor.encode() // This can be saved into coredata/UserDefaulrs
let newColor = UIColor.color(withData: myColorData) // Converting back to UIColor from Data

You can use SwifterSwift hexString to save a string to coredata and then retrieve it like below

let str = UIColor.white.hexString

let color = UIColor(hexString:str)