How to save a UIImage in Core Data and retrieve it

Way simpler than I had thought: Core Data can save binary NSData objects – all we have to do is declare the attribute as “Binary Data” in our model.

Screen Shot 2014-01-06 at 20.52.21

Optionally you can choose to “Allow External Storage” for the attribute, which means that the data is not stored in the database (to be honest, I don’t know where – Core Data takes care of everything). Not a good choice if you plan to export the store file, or populate database changes to other stores via iCloud.

Screen Shot 2014-01-06 at 20.57.15

To save an image, we’ll turn it into data and add it to our managed object (Event in my case):

self.myEvent.picture = UIImageJPEGRepresentation(chosenImage, 1);

To retrieve it from Core Data, we’ll do the opposite:

self.imageView.image = [UIImage imageWithData:self.myEvent.picture];

I have tried this successfully in iOS, works like a charm.

In Cocoa however I believe an NSImage needs an NSValueTransformer for this operation.





Leave a Reply