Storing Data in Core Data: UIImage

Proceed with caution

Steven Curtis
4 min readFeb 6


Photo by Luke Chesser on Unsplash

Difficulty: Beginner | Easy | **Normal** | Challenging

You probably shouldn’t be doing this. You probably shouldn’t be doing this.

Core Data can store data, but storing large images like this? Probably you want to use file. But I can see that you **really** want to store UIImage. In that case, let us strap in and get going.



Core Data: A framework that allows you to manage the model layer objects in your application. Core Data does this by being an object graph management and persistence framework.

The image to store

In Assets.xcassets I’ve added three Placeholder images.

So…surely I can place this image into core data…right?

This involves adding an image attribute to the core data entity, and give it the type Binary Data.

This Binary Data will, fairly obviously, be the data from an image, and for this I can use the useful pngData() like:

let image = UIImage(named: "Placeholder")
let imageData = image?.pngData()

Setting Binary Data

The type for the image is actually Binary Data.

Saving the Data

You need to be mindful about using the existing `managedObjectContext` to perform your changes:

func save(data: Data, completion: @escaping ( ()-> Void) ) {
managedObjectContext.perform {
let imageObject = NSManagedObject(entity: self.entity, insertInto: self.managedObjectContext)
imageObject.setValue(data, forKey: Constants.imageAttribute)

self.saveContext(completion: {

For more details about this take a look at the attached Repo.

Improving Performance