Search code examples
iosswiftcore-dataswiftui

How to store type Color from SwiftUI into CoreData?


I tried to use Transformable type in core data but the Color can not be cast into NSObject. What should I do if I want to store the Color information?


Solution

  • You can use Transformable, although it has to be stored as UIColor and not Color:

    The withRootObject is the colour you want to save.

    Also keep in mind that myColour should be of type Data:

    @NSManaged public var myColour: Data?

    Then you can archive the data like the following:

    do {
        try obj.myColour = NSKeyedArchiver.archivedData(withRootObject: UIColor.blue, requiringSecureCoding: false)
    } catch {
        print(error)
    }
    

    Retrieve it using:

    func getColour(data: Data) -> Color {
        do {
            return try Color(NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: data)!)
        } catch {
            print(error)
        }
    
        return Color.clear
    }
    

    Usage:

    Text("This is some blue text.") // we saved it as UIColor.blue earlier.
        .foregroundColor(self.getColour(data: self.data.myColour!))