In one of the previous articles we learned how to insert data into the Sqlite database using FMDB wrapper. Apple also provides a built in data management library known as Core Data. Core Data is an object relational mapper which can be used to perform CRUD operations on a Sqlite database. In this article we are going to learn how to use Core Data in our application.

Getting Started:

To get started create a new project as an “Empty Application” and in the next screen select “Core Data” which will ensure that Core Data will be plugged into the application. Checkout the screenshot below to get a better idea:



A new Core Data file will be generated with the extension xcdatamodelId. This is our model file which will map to the database. Just like any other Object Relational Mapping tool the Core Data uses the Active Record (link) pattern. Active Record pattern indicates that the column names will be mapped to the properties and the table name will be mapped to the classes.  

Open the AppDelegate.h and AppDelegate.m file and you will notice that xCode has already declared classes required for the Core Data framework. In the next section we are going to create our model.

Creating Core Data Model:

Click on the model file which ends with the xcdatamodelId and you will see the empty model. At the bottom you will see an option to add an entity. Click on the button and start building your entity. You can add attributes to an entity using the “Add Attributes” button. When you are finished your model will look something like this:



You can also use the graph editor style to view and add attributes as shown in the screenshot below:



Our first model is complete! In the next section we are going to insert data into the Sqlite database using our Core Data model.

Inserting Data into Sqlite Using Core Data:

Inside the AppDelegate.m “didFinishLaunchingWithOptions” method implement the following code:



NSManagedObjectContext is responsible for keeping track of all the changes in the model objects. NSManagedObjectContext is also responsible for all the CRUD operations performed by the Core Data framework on the Sqlite database.

NSManagedObject represents the model class which will be persisted in the database. The properties associated with the model class can be accessed using the key-value pair. After making the changes run the application and your new model will be persisted in the database.

To make sure that the model is persisted in the database you need to visually see the records in the database. At this point you have no idea where the database is stored. This mystery can easily be solved if you put a break point in the “persistentStoreCoordinator” method and take a look at the storeURL path. Here is the value of storeURL which we displayed on the console:



Browse to the above path and you can see the database “FruitMarket.sqlite”. There are many tools to visually see the contents of the database. For the sake of simplicity we will use the SQlite AddOn for Firefox. The following screenshot shows the FruitMarket database opened using the SQlite:



Although the above code works perfectly but we can still make it better. Currently, the model is exposed as NSManagedObject class which allows us to access the properties/attributes using key-value syntax. Core Data allows to create the model classes which are subclasses of NSManagedObject class. Open the Core Data model and then click on Editor and select “Create NSManagedObject Subclass” as shown in the screenshot below:



xCode will create two entity classes “Fruit.h” and “Fruit.m”. The implementation of these files is given below:



Now instead of using NSManagedObject as our entity we can utilize the newly generated “Fruit” classes in our code:



As you can see the above code is much simpler than our previous implementation. In the next section we are going to demonstrate how to retrieve information from the database.

Retrieving Models from Core Data:

The retrieval is performed by using the NSFetchRequest object. The returned model is a complete object with all the attributes populated. The implementation below shows the method “getFruits” which returns all the fruits stored in the “FruitMarket” database.



Adding Model Version Control:


The current “Fruit” model exposes two properties “name” and “calories”. We are going to add one more property “color” to our “Fruit” model.

After the property is added to the model you need to generated new subclass by using the “Editor->Create NSManagedObject SubClass”. This will generate a new subclass with the new property “color” added to the model.

If you try to run the application at this point then you will notice that it errors out. The Core Data framework is still pointing to the older model. You will need to assign the new model version so that Core Data can recognize it. Select “Editor->Add Model Version” then assign a new version number. After adding a new version number you need to tell the main model file to use the latest version of the model. Click on the “FruitMarket.xcdatamodeld” file and then from the menu on the right hand side select the Core Data model correct version

Now your Core Data is aware of the model changes and it will allow you to persist the new attributes in the database.

NOTE: We have experienced that updating the columns in the sqlite database by manually adding columns does not work. If you want to reflect your new model changes in the database schema you first once persist the new model to the database.    

Conclusion:

In this article we scratched the thick surface of the Core Data API. We learned how to persist and retrieve information from the Sqlite database. In the future articles we are going to further explore the features provided by the Core Data.

[Download Sample]