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

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

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

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

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.