AlliOSObjective CTutorial

Step by Step Core Data with MagicalRecord in Objective C

If you are looking for the most easiest and simplest approach of implementing core data with MagicalRecord and that covers all the aspects like storing data from a form (UIText Fields) and from web-service (JSON response) you are at the right place.
This tutorial covers step by step process of how to implement core data with MagicalRecord. I’m assuming that the reader have basic knowledge of what core data is. Not the code part but just the general concept of why we use core data.

So what my understanding of core data is that… It’s a data storage type thing! But here your data is your objects. For example if you are displaying countries you can download the countries via web service using AFNetworking of AlamoFire or anything else and store it in your CoreData Entity and later in the app you can call it and it’ll be loaded fast. So this is just one example out of many of core data.

About the Project:

Imagine a scenario in which you’re the HR of a company in United States. It’s the new year’s beginning and you want to make the calendar for your company. In which you have to add national holidays as well as company’s own personal holidays.
From this scenario we can extract the following information:

  • Add/Edit National Holidays
  • Add/Edit Custom Holidays
So for national holidays we will use this API to fetch national holidays of US. Go ahead and sign up as you’ll be need an API key.
For custom holiday we will make a view controller with text fields and buttons.
All of the data will be handled by Magical Record. Magical record is just a wrapper of Core Data. So as you can see it’ll cover all the things. So let’s dive into it.

Setting up the project:

I’m not going to spend time of this part as it is very generic and only making and setting up the UI. So let me quickly show you how my UI is looking so that you can make and match to it.
Start xCode make a new project > name it. DO NOT check Core Data while creating a new project. As we will be creating it with Magical Record so it will do all by itself.
Make the UI as shown in the picture below:
UI of an IOS app in xcode
The Root Controller is USHolidays Embedded in Navigation Controller. It contains of a table view with a prototype cell and this cell has two labels i.e. Holiday Name and Date.
There are two bar buttons available on navigation bar named as ADD and EDIT.
The second view controller is add/edit view controller. Containing two text fields one for name and one for date. And a UIButton with title add.
Next add two type of cocoa touch classes.
  1. AddEditViewController which is the subclass of UIViewController
  2. HolidayTableViewCell which should be the subclass of UITableViewCell
Assign both classes to their controllers i.e. AddEditViewController to the view controller of Add Edit View Controller and HolidayTableViewCell to the prototype cell of tableview. And also set table view data source and delegate to self and add <UITableViewDelegate, UITableViewDataSource> to your ViewController.h
Next make outlets of all the elements you’ve placed on the storyboard in their respective classes.

Ground work for MagicalRecord (MR):

So as we are getting into MagicalRecord. I’ll be using MR as short of MagicalRecord from now on.
We need to lay some groundwork. So first thing to do is to add libraries we will be using in this project. Go ahead and add these following libraries in your project (Using Pods is recommended).
After successfully configuring them in your project we need to add the data model. So again add a new file
and this time select core data > data model
Name it and create it. Next open the .xcDataModeld file and create a new entity and name it Holiday
After that click the + icon and add two attributes named holidayDate and holidayName of type string
add entities in core data model
Next choose Editor from Menu and select Create NSManagedObject Subclass…
Select entity and click next it’ll create four class for you.
nsmanaged object subclasses
That’s it for the ground work.

Getting started with MagicalRecord:

If you have a Precompiled Header file (.pch) in your project go ahead and add #import <MagicalRecord/MagicalRecord.h> in it. If you don’t then just add this link in your AppDelegate.h
In your AppDelegate.m method didFinishLaunchingWithOptions add [MagicalRecord setupCoreDataStack];
This is it for the importation of magical record. Now remember I said DIDN’T check the core data while creating the project, it was because of this. This one line code has taken care of all the things.
Next we have divided this tutorial into following part:
  • Add/View Custom Entry
  • Delete Entry
  • Edit/Update Entry
  • Fetch Holidays from API and Perform MR

Add/View Entry:

Open ViewController.h and import the following:

After @interface and before it’s @end add a new property:
Next after viewDidLoad method add a new method -(void)fetchHolidays as:
So what this fetch holidays is doing it is fetching all the data in holiday entity and storing it in our array.
Now in your viewDidLoad method add [self fetchHolidays]; so that when the view is loaded it’ll load the latest data into our array.
Next we implement the tableview delegate and datasource methods
And in cellForRowAtIndexPath method we will use our NSManagedObject Subclass i.e. Holidays to access the attributes in our holidays entity,
Go Ahead and run the project. You’ll find nothing in the table. This is because there is nothing in your entity. So to add a custom holiday so we need the add button in our navigation bar to show us that view controller. In you add button IBAction add:
Before we move to AddEditView Controller add viewWillAppear method to refresh tableview every time the view is loaded.
Go ahead and open AddEditViewController.h and again import

As I’m not using pch so you see we have to add it to every class. So using .pch is recommended

Other than the IBOutlet and Actions in .h file we need a property of our entity so add it as

The reason  why we need this property is to check weather it is editing an entry or adding a new one. Edit is covered in the next section for now let’s see the add functionality.

This class implementation is very simple. We only need to add code to our add button. I’m not going to check if the text fields are empty or not I’m just going to add them.

First we will check self.holidaytoAddEdit that if there is no value attached to it then create a new one. If there is value attached to it this means we didn’t need to add a new one we just update it.
So it’s pretty clear that if there is no value attached to self.holidaytoAddEdit then MR should create entity as it’ll be a new value.
If you run the code now you’ll see you can add a value and it’ll be displayed on the table view. Quit the app and open it again and you’ll see the entries are already there.
This ends the add and view part of core data with MR.

Delete Entry:

In ViewController.h we have edit bar button in navigation bar. This work will start from it’s IBAction. Update it’s IBAction method as:
As you can see there are only two lines of code. The first line is a default table behaviour that check if tableview isEditing or not and vice versa.
Second line is the one liner if condition you can say that if tableview isEditing then sender which is uiBarButton edit button change it’s title to Done otherwise keep it as edit.  (NOTE that this edit doesn’t mean editing and update.)
It’s means editing the rows. The edit/update entry feature is done in the next section
So as it is a table view thingy so we need to add two more tableview delegate methods.

This method is just telling that this row is editable.

I’ve added comment on every line that explains. Run the project and you can see you can easily delete entries now.

Edit/Update Entry

To add edit option let user select/tap on the specific cell he wants to edit. So for this purpose we need to add a very common delegate method in ViewController.m:
 Open AddEditViewController.m and in it’s viewDidLoad add
So Inside if the first line is changed the title of addButton from Add to Update. The next two are setting the text of UITextFields to the object we have received from ViewController.m of our app.
The functionality of add button is already configured there is no need to change it. Go Ahead run the app and edit some entries.

Fetch Holidays from API and Perform MR:

In your ViewController.m after #import statements add
Just above the @property you made in @interface i.e. holidayArray add after @interface
Make a method call in viewDidLoad as [self getAllHolidaysForCountry:@”US”]; and it’s implementation is as follows:

This is the example which help me get started on core data but the story doesn’t end here. CoreData has another important concept which is called Relationships. Here is the post that covers Relationships with in CoreData using Magical Records.

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.