Storing UIColor object in Core Data

前端 未结 4 2069
感情败类
感情败类 2020-12-01 14:18

I want to store a UIColor object as an attribute on a Core Data entity, then retrieve it and use it in the same fashion that I do the other attributes on that entity.

<
4条回答
  •  醉话见心
    2020-12-01 15:04

    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
    

提交回复
热议问题