Best way to save and retrieve UIColors to Core Data
I have made Swift 3 version of Oleg's answer with some modifications on the code.
extension UIColor {
class 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 {
class 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
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];