Save and Retrieve UIImage using MagicalRecord CoreData is as simple as storing strings. Because we will be saving UIImage and then we will Retrieve it to display it.

First of all make an entity with two fields:

  • dataString of type transformable
  • fileName of type string
entity in core data

Type transformable is defined in details in this post. We will get to that part later in this post.

If you don’t know how this was made read step by step core data with MagicalRecord first. After that create NSManagedObject Subclass for this entity. I’ve named it PatientFiles.

Open your ViewController.h and do the following:

  1. Import NSManagedObject Subclass
  2. Add delegates and data source of UIIMagePicker, NavigationController and tableView
  3. Make one IBOutlet and one IBAction and connect it with their perspective UI elements. It clearly states that you need a tableView and a button (preferably in Navigation bar).

Make a prototype cell with one UIImageView and a UILabel as:

tableview with prototype cell

This is a good time to make a new class called AttachmentTableViewCell and connect cell elements to their IBOutlet:

We don’t need to do anything else in this class. Open ViewController.m and Import #import “AttachmentTableViewCell.h” and after @interface addAttachmentsViewController add:

In viewDidLoad add the following:

After viewDidLoad let’s add viewWillAppear:

Let’s remove the two error you’re getting by implementing fetchAttachments method.

Next we will make two methods one for take photo and other for choose photo from library.


Now implement tableView Delegate and DataSource methods:

In the code snippet above the comment that said assigning image is the one which is assigning. As our attribute type is Transformable it means this field can have any object. It can be an array, image or anything that you can say has an id. So we have converted it to UIImage because we know that we will be storing UIImage in it.

To store UIImage in our transformable we implement imagePickerController Delegate Methods. There are two methods we will be implementing. First one is didFinishPickingMediaWithInfo which is called when user selects an image. It can be either from library or from camera. When user has selected to go ahead with image this method is called. Second one is imagePickerControllerDidCancel which is when use didn’t selected any image and just cancelled.

Now everything is set and good to go. There is just one thing which is left. Now we will show UIActionSheet when addNewAttachmentButtonPressed:

Run the code and see changes. Here is how your final product will look like:

Tags : how to store images in core data magicalrecord
Chaudhary Talha

The author Chaudhary Talha

I'm an iOS developer by profession and UI/UX designer by passion. All my tutorials are based on my personal experiences and whenever I learn something new I share it with the world.