Saving Images to Core Data in iOS

Create Xcode project with Core Data

First, create a new Xcode project (with Core Data checkbox checked) with an imageView and two buttons. Create an @IBOutlet for the image and @IBActions for the buttons, and name accordingly. One button will be used for saving the image, the other will be used for retrieving the image:

Create Core Data Entity

Next, we’ll create a single entity in core data with an ‘image’ attribute. Open the model file and add an entity named ‘Photo’ with an attribute of ‘image’. Select the data type of ‘binary data’ for the image attribute. With the ‘Photo’ model selected, go to the Data Model inspector on the right and for ‘codegen’, select manual mode:

Saving the image to Core Data

Add the following code for the save image action:

Retrieving the image

Add the following code to the retrieve image action to retrieve the last image in the array of Photo images:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store