Saving Images in Core Data

A common question I see on Swift developer forums is how to save images in Core Data. You have to do the following to save an image in Core Data:

  • Add an attribute for the image with data type Binary Data.
  • Use external storage to save the image in a separate file.
  • Convert the image to a Data object to save it in Core Data.

Add Attribute of Type Binary Data

Core Data does not have a data type specifically for images. Binary data is the closest data type that Core Data supports.

Use External Storage

Images take a lot of space so it’s more efficient to save them in separate files instead of saving them in the persistent store where Core Data saves your app’s data.

To tell Core Data to save the image in its own file, select the attribute and open the data model inspector. Choose View > Inpsectors > Data Model to open the data model inspector.

use external storage

Select the Allows External Storage checkbox to save the image in a separate file.

Convert the Image to a Data Object

You must convert the image to a Data object to set the image attribute’s value in your code. Data is the underlying data type for a Core Data attribute of type Binary Data.

Swift apps generally use either UIImage or NSImage to work with images. UIImage has pngData and jpegData functions to convert an image to Data. NSImage has a tiffRepresentation function to convert to Data.

Get the Swift Dev Journal Newsletter

Subscribe and get exclusive articles, a free guide on moving from tutorials to making your first app, notices of sales on books, and anything I decide to add in the future.

    We won't send you spam. Unsubscribe at any time.