Best Way to Save and Retrieve Uicolors to Core Data

Best way to save and retrieve UIColors to 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];

Store and retrieve UIColor from Core Data using swift 5

Try the following for Swift 5

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)
}
}

Storing UIColor object in Core Data

Your attribute should be of the type Transformable. The default value transformer (NSKeyedUnarchiveFromDataTransformerName) can transform any object that conforms to NSCoding.

  1. Mark the attribute as type "Tranformable".
  2. Optional: Set the Value Transformer Name to "NSKeyedUnarchiveFromDataTransformerName". If you do not, it will default to this anyway.

Like so

You do not have to do anything else. Keep in mind you will not be able to match transformable attribute with a predicate or sort by them. They are pretty much just storage - the value transformer transforms the object value into NSData, which is what gets persisted in the store. When the attribute fault fires Core Data uses the transformer in the other direction to go from NSData to your object type.

How to store type Color from SwiftUI into CoreData?

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!))

How can I correctly save transformable objects in core data?

The linked article covers the topic very well. The log in the console you are getting is not an error, but a warning. We have encountered the same issue and every solution points to using NSSecureUnarchiveFromData which in fact seems to be a correct one for the problem. We have been using it in production for quite a while now and everything works as expected and the warning is gone. And you should be treating it for what it is, a warning. It it does resurface at any time for some specific type that you are trying to store in your CoreData, you could try implementing a custom transformer just like its shown in the article. Good luck!

Core Data data model: attribute type for UIColor

What you probably want is a transformable attribute. Give the section on "Non-standard Persistent Attributes" in the Core Data Programming Guide an other read. A transformable attribute is, underneath the covers, a binary data attribute, but Core Data will automatically use the NSValueTransformer of your specification to serialize and unserialize the logical attribute value for you. For values that are NSCoding compliant, the NSKeyedUnarchiveFromDataTransformerName (which is the default transformer) will do the trick.

Of course, Core Data cannot index or, for an SQLite backend, query against this transformable value.

CoreData Swift: How to save and load data?

Saving data:

var person = NSEntityDescription.insertNewObjectForEntityForName("Person", 
inManagedObjectContext: self.managedObjectContext!) as Person
person.name = "Mary"
person.age = Float(arc4random() % 100)

var error : NSError? = nil
if !self.managedObjectContext!.save(&error) {
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}

Loading data:

var error: NSError? = nil
var fReq: NSFetchRequest = NSFetchRequest(entityName: "Frases")
fReq.predicate = NSPredicate(format: "id contains[c] %@", String(day))
var sorter: NSSortDescriptor = NSSortDescriptor(key: "id" , ascending: false)
fReq.sortDescriptors = [sorter]
fReq.returnsObjectsAsFaults = false
let result : [AnyObject] = self.managedObjectContext!.executeFetchRequest(fReq, error:&error)!

what's the correct way to store an NSURL in Core Data?

Ok... It's been 14hrs straight of coding.. I'm an.. eh.. idiot:

I forgot to access the attribute in the ArchivedID object. That is:

NSManagedObjectID* ID = [managedObjectContext.persistentStoreCoordinator managedObjectIDForURIRepresentation:[defaultConfiguration.archiveID anyObject]];

should be

NSManagedObjectID* ID = [managedObjectContext.persistentStoreCoordinator managedObjectIDForURIRepresentation:[[defaultConfiguration.archiveID anyObject] idURI]];


Related Topics



Leave a reply



Submit