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?
In order to save a UIColor to core data you need to separate the red, blue, and green values. Then, within your creation code, fetch the RGB values and create a UIColor object with the fetched results.
When you declare a property as Transformable Core Data converts your custom data type into binary Data when it is saved to the persistent store and converts it back to your custom data type when fetched from the store. It does this through a value transformer.
To save an object with Core Data, you can simply create a new instance of the NSManagedObject subclass and save the managed context. In the code above, we've created a new Person instance and saved it locally using Core 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];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With