Mobile - - By Kanya Srinisavan

iPhone Application Development – Core Database

iPhone Application Development

The need to save data in the device is a very common requirement for any mobile application. This would enable the users to access the application when offline and also help in accessing the data faster.

There are lots of ways through which we can persist the data in the device. One of the best ways is to use a core database to store the data in the device.

Create a new application ‘DBExampleApp’ with the ‘Use Core Data’ option selected.

We will use the same ‘Articles’ example from our previous tutorial. We will modify the example and we shall save the articles in the database and retrieve the articles from the database and show it in the list.

You’ll find a link to download the full source code at the end of this tutorial.

What are we waiting for?

Excepting the Appdelegate files, add all the files from the previous example into the new project. Remember to delete all the lines except the return statement in the ‘appDidLaunch’ method. Also add the ‘Main Storyboard file base name’ property in the ‘DBSampleApp-info.plist’ file.

The initial settings are done. Run the app to ensure that everything works perfectly.

We will find additional variables and methods in the appdelegate files. These extra codes get auto generated if we create an application with the ‘Use Core Data’ option enabled.

A data model file ‘DBSampleApp.xcdatamodeld’ is also auto generated.

Knowing certain core data terminology is mandatory in order to understand the methods and variables in the appdelegate files.

Persistence Object Store: Refers to the way in which the object is stored. A Persistent object store can be an sqlite database, XML, File etc. The underlying persistent object store in the core database is an sqlite database.

Managed Object Model: Represents the database schema. It contains the entities or tables in the database, its attributes or fields and their relationship with each other. The data model file ‘DBSampleApp.xcdatamodeld’ represents a managed object model.

Entity Description: In our example, ‘Article’ is an entity. Article’s name and description denotes the entity description.

Managed Object: Instances of an entity represents the managed object.

Managed Object Context: It allows us to modify and manage objects in the database. It is referred as a scratch pad as it maintains the undo/redo history of the database. Operations like insertion, retrieval and deletion of objects in the database are done with the help of the managed object context.

Persistence store coordinator: It coordinates between the persistent store and the managed objects of the application.

Having understood the database concepts, now try and understand the methods and variables in the appdelegate files.

Select the ‘DBSampleApp.xcdatamodeld’ file and create a new ‘Article’ entity. Add title and description fields as shown below.

create a new Article entity


Select the attribute

Select the attribute and check its properties in the attribute inspector.

Transient – Attributes are not persisted in the persistence store. Their value is based on other field values and are usually calculated at run time.
Optional – Specifies mandatory or not.
Indexed – Denotes Primary key attribute

Let’s also create a ‘User’ Entity to understand the relationship concept in the core database. Add attributes ‘userId’ and ‘username’ for the ‘User’ entity.

One user can write many articles, so create a one-to-many relationship between the user and the article entity.

Change the Editor Style at the bottom of the data model window to ‘Graph’. Press CTRL and drag from the ‘User’ Entity to the ‘Article’ Entity. Set the attributes of the relationship as given below.

Set the attributes of the relationship

Delete Rules

Let’s look at it from the perspective of the user entity.

Cascade: Deleting the user object deletes all the articles associated with it.
Deny: The user object cannot be deleted unless and until the entire article objects are deleted.
Nullify: If the user object is deleted, the inverse relationship ‘author’ will be set to null provided ‘author’ is an optional relationship.
No action: No action is required at the ‘Article’ entity on deletion of the user objects.

Select the entity and select Editor -> Create NSManagedObject Subclass.

Article and User managed object classes will be generated on selection of the entities in the subsequent dialog boxes.

Add Object to the Database

NSManagedObjectContext *context = [appDelegate managedObjectContext];
    Article *articleDetails = [NSEntityDescription
    [articleDetails setValue:strName forKey:@"articleTitle"];
    [articleDetails setValue:strArticleDesc forKey:@"articleDesc"];
[appDelegate saveContext];

Create an ‘extern’ appdelegate variable to access the variables and methods in the ‘SPTAppDelegate’ Classes.

Any database operation can be done only with the help of managed object context.

We have created an instance of the Article Entity and set the values of the variables ‘strName’ and ‘StrArticleDesc’ for the attributes in the entity.

The values are written in the database with the help of the save context method in the Appdelegate.

Let’s create a user object and establish a relationship between the newly created article object and the user object.

User *userObj = [NSEntityDescription
    [userObj setValue:[NSNumber numberWithInt:123] forKey:@"userId"];
    [userObj setValue:@"Kanya" forKey:@"username"]; = userObj;
    [appDelegate saveContext]

Fetch Objects from the Database

NSError *error;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Article" inManagedObjectContext:[appDelegate managedObjectContext]];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    for (Article * articleObjin fetchedObjects) {
        NSLog(@"Title: %@", [articleObj valueForKey:@"articleTitle"]);

NSFetchRequest is used to fetch the objects from the database. The entity on which the fetch operation should be performed is mentioned. An array of entity objects is returned when the fetch request is executed.

The conditions that should be applied while executing the fetch condition can also be mentioned using the NSPredicate class as given below.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author.userId == %@",[NSNumber numberWithInt:111]];
    [fetchRequest setPredicate:predicate];

If the above line is added before the fetch request is executed, articles corresponding to the user will be returned.

We can also sort the fetched objects based on some attribute using the NSSortDescriptor class as given below

NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"articleTitle" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDesc]];

The objects returned will be sorted in the ascending order based on the article title.

Update Objects in the Database

NSError *error;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Article" inManagedObjectContext:[appDelegate managedObjectContext]];
    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"articleTitle == %@",@"Sample Article"];
    [fetchRequest setPredicate:predicate];
    NSArray *fetchedObjects = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if([fetchedObjects count] > 0)
        Article *articleObj = [fetchedObjects objectAtIndex:0];
        articleObj.articleDesc = @"Sample Article Desc";
    [appDelegate saveContext];

Updating an object in the database is similar to adding objects in the database. We need to fetch the object that we want to update with the help of predicates and then update the required attributes of the object.

Delete Objects from the Database

NSError *error;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Article" inManagedObjectContext:[appDelegate managedObjectContext]];
    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author.userId == %@",[NSNumber numberWithInt:123]];
    [fetchRequest setPredicate:predicate];
    NSArray *fetchedObjects = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    for (Article *articleObj in fetchedObjects) {
        [appDelegate.managedObjectContext deleteObject:articleObj];
    [appDelegate saveContext];

We have fetched the object and deleted it using the ‘deleteObject’ method of the managed object context.

Remember to call the ‘saveContext’ method when you want to commit the changes to the database.


By the end of this tutorial, you should be able to perform all the basic core database operations.

Try to use the operations learned above and make the previous example work with the core database integration.

Download the full source code and check out how core database is integrated.

Login or Create Account to Comment
Login Create Account