OWolf
OWolf

Reputation: 5132

Best way to save and retrieve UIColors to Core Data

I can think of a few ways, for instance saving each color component as a float, saving an array as transformable. Saving a color from pattern image could be slightly more complicated, but I guess you could save the name of the image as a string and insert that into creation code.

Am I on the right track, else what is the best and most efficient to do this task in general?

Upvotes: 15

Views: 7258

Answers (2)

Anand
Anand

Reputation: 5332

I have made Swift 3 version of Oleg's answer with some modifications on the code.

extension UIColor {
    func color(withData data:Data) -> UIColor {
         return NSKeyedUnarchiver.unarchiveObject(with: data) as! UIColor
    }
    
    func encode() -> Data {
         return NSKeyedArchiver.archivedData(withRootObject: self)
    }
}

Swift 5 version of Extension

extension UIColor {
        
     func color(data:Data) -> UIColor? {
          return try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UIColor
     }

     func encode() -> Data? {
          return try? NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false)
     }
}

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

Upvotes: 12

Oleg
Oleg

Reputation: 3014

You can convert your UIColor to NSData and then store it:

NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:[UIColor blackColor]];

then you can convert it back to your UIColor object:

UIColor *theColor = (UIColor *)[NSKeyedUnarchiver unarchiveObjectWithData:theData];

UPD.:

Answering your question in comments about storing the data, the most simple way is to store it in NSUserDefaults:

NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:[UIColor blackColor]];
[[NSUserDefaults standardUserDefaults] setObject:theData forKey:@"myColor"];

and then retrive it:

NSData *theData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
UIColor *theColor = (UIColor *)[NSKeyedUnarchiver unarchiveObjectWithData:theData];

Upvotes: 16

Related Questions