使用ValueTransformer将{UIColor存储在核心数据中

时间:2016-07-14 20:31:28

标签: swift core-data nsvaluetransformer

我正在尝试将UIColor存储在Core Data中(我不想将其存储为String),我想使用NSValueTransformer。我写了下一个ValueTransformerclass(toHex()它是我的扩展,将颜色转换为十六进制字符串),但每当我尝试保存数据(如object.color = UIColor.blackColor())时,我收到崩溃,出现无法读取的错误消息«无法识别的选择器发送到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 个答案:

没有答案