Store UIColor in Core Data with ValueTransformer

507 views Asked by At

I’m trying to store UIColor in Core Data (I don’t want to store it as String), I want to use NSValueTransformer. I’ve written next ValueTransformerclass (toHex() it’s my extension that converts color to hex string), but everytime when I try to save data (like object.color = UIColor.blackColor()) I receive crash with unreadable error message «Unrecognized selector sent to 0xf93».

class ColorTransformer: NSValueTransformer {
    override class func transformedValueClass() -> AnyClass {
        return NSData.self
    }

    override class func allowsReverseTransformation() -> Bool {
        return true
    }

    override func transformedValue(value: AnyObject?) -> AnyObject? {
        let color = value as? UIColor

        guard let hex = color?.toHexString() else { return nil }

        let hexString = NSString(string: hex)

        return hexString.dataUsingEncoding(NSUTF8StringEncoding)
    }

    override func reverseTransformedValue(value: AnyObject?) -> AnyObject? {
        guard let hexData = value as? NSData,
            let hexString = NSString(data: hexData, encoding: NSUTF8StringEncoding) else { return nil }


        return UIColor(hexString: String(hexString))
    }
}
0

There are 0 answers