0

Hello I just want to save a UIColor Attribute in CoreData but I get the warning: "'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release"

CoreData Attribute color

I access the attribute simple like this: entry.color

I know this articles which explains what is the problem and how to solve it in general.

https://www.kairadiagne.com/2020/01/13/nssecurecoding-and-transformable-properties-in-core-data.html

https://danielbernal.co/coredata-transformable-and-nssecurecoding-in-ios-13/

I just thought why isn't there a example code especially for UIColor, I think many devs need exactly this.

Edit:

I changed it from Transformable to String and used this extentions, of course small tweaks in the main applications are necessary, but it works :)

// https://stackoverflow.com/questions/14051807/how-can-i-get-a-hex-string-from-uicolor-or-from-rgb/40018698
extension UIColor {
      func toHexString() -> String {
          var r:CGFloat = 0
          var g:CGFloat = 0
          var b:CGFloat = 0
          var a:CGFloat = 0

          getRed(&r, green: &g, blue: &b, alpha: &a)

          let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0

          return String(format:"#%06x", rgb)
      }
  }
// https://stackoverflow.com/questions/1560081/how-can-i-create-a-uicolor-from-a-hex-string
extension UIColor {
    convenience init(hexaString: String, alpha: CGFloat = 1) {
        let chars = Array(hexaString.dropFirst())
        self.init(red:   .init(strtoul(String(chars[0...1]),nil,16))/255,
                  green: .init(strtoul(String(chars[2...3]),nil,16))/255,
                  blue:  .init(strtoul(String(chars[4...5]),nil,16))/255,
                  alpha: alpha)}
}
Java
  • 323
  • 3
  • 15

0 Answers0