Monday, February 28, 2011

using core data to save data from app

In my earlier post I have tried to explain what core data is and in this post we will be seeing how to add data and retrieve data using the Core data framework and in my next post I will be showing how to use predicate and retrieve data.

Design Phase: I won’t be using any design for this app, instead i will write some code and display the output on the console, So I have used only the appDelegate files here.

 Step 1: Open Xcode and select Windows based core data application template, see the image given below

Once the above process is done you will see two files in your project those are yourProgramNameAppDelegate.h and yourProgramNameAppDelegate.m file. Now the best part about core data is that some piece of code will be added in your application which you don’t need to worry about. 

If you open the AppDelegate.m file you will be able to see that piece of code, this piece of code says that “ I will be setting getter and setters for the properties written in the .h file of the app delegate and also will be creating a .SQLITE file in the document directory”, the sqlite file is created just once not every time.

Now just expand the resources group and what you will see is a file with the extension .xcdatamodel, select that file. Now you must be seeing a view which is exactly like the view in the image given below.


This is the interface provided by apple so that you can create some entities and gives the  relationship between them. For our demo I will be creating a parent and a child relationship with one key concept in mind i.e. “A parent can have multiple child but a child will have only one parent”.

Step 2: This step deals with creating entities, assigning attributes to them and assigning relations between them.

In the above picture you can see an entity tab and a add button which is at bottom, click it. Now you must see a pop-up with the name entity. 
Inorder to assign name to this entity, select the entity tab.

Now its time to add some attributes to the parent entity.

You can see the second tab which is called as property,select your entity and click the add button from the property tab. This will add a new attribute to the parent entity give the attribute a name and a type

Similarly, add the attribute called Mothername also add a new entity called Child and it’s attribute called Childname.

Once the above process is completed then you will have a view which looks somewhat like this

Now its time to give them relationships with the help of the line tool (see the above image at the bottom you must be seeing an arrow, a line, select the line form there). 

So as said earlier a child will have only one parent but a parent may have multiple children, so in this case what we must do is  to use the line tool and make a single relationship between them and name that relationship as childToParent and specify the delete rule for that as well, I have specified the delete rule as cascade. Make sure that you start the line from child to parent

Now you have to specify the parent to child relationship as one-to-many relationship with the settings as specified in the image given below

It’s time to add the managed object files for the relationships that you made so far, for that you have to select the entire entity(Parent and Child) and then select the xcode project file from your application (This is the blue file that appears on the top) here’s a snapshot to guide you.

Once you add this file their will be a window in front of you just hit next until this screen arrives

and then click finish once this process is done xcode will add four new files in your project and the name of those files are Parent.h, Parent.m and Child.h and Child.m.

As said earlier in core data we manipulate the entities with the help of objects,these files are called as Managed object files and when they will be added in your application it will look some what like this

Now its time to do some actual coding

Step 3: Select the appdelegate.h file and add two functions with the name

-(void) reteriveData;

now select the appdelegate.m file and give body to those functions here's the code to do that
but before you proceed with the code make sure you have imported the files of parent and child in the appdelegate.m file

#import "CoreDataAppAppDelegate.h"
#import "Parent.h"
#import "Child.h"

Parent *p1 = [NSEntityDescription insertNewObjectForEntityForName:@"Parent" inManagedObjectContext:self.managedObjectContext];
p1.Mothername= @"Asha";
p1.FatherName = @"Radhe";
Child *c1 = [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:self.managedObjectContext];
c1.ChildName = @"Radix";
[p1 addParentToChildObject:c1];
Parent *p2 = [NSEntityDescription insertNewObjectForEntityForName:@"Parent" inManagedObjectContext:self.managedObjectContext];
p2.Mothername = @"Chichi";
p2.FatherName = @"Goku";
Child *c2 = [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:self.managedObjectContext];
c2.ChildName = @"Gohan";
[p2 addParentToChildObject:c2];
if([self.managedObjectContext hasChanges])
[self.managedObjectContext save:nil];

Code Explanation: In the above code i am adding values to the parent and child class and saving them into the database. The line

[p1 addParentToChildObject:c1]; 

says that the child c1 will be assigned or added in relation with the parent p1

Now its time to give body to the other function and here's the code to do that as well

-(void) reteriveData
NSFetchRequest *fetchReq = [[NSFetchRequest alloc]init];

[fetchReq setEntity:[NSEntityDescription entityForName:@"Parent" inManagedObjectContext:self.managedObjectContext]];
NSMutableArray *resultArray = [[NSMutableArray alloc]initWithArray:[self.managedObjectContext executeFetchRequest:fetchReq error:nil]];
for(Parent *pnt in resultArray)
NSLog(@"Mother name is %@",pnt.Mothername);
NSLog(@"Father name is %@",pnt.FatherName);
for(Child *cld in pnt.ParentToChild)
NSLog(@"Child name is %@",cld.ChildName);

Code Explanation: In order to fetch any particular data in core data we have to use a class called NSFetchRequest and its instance methods, The line

[fetchReq setEntity:[NSEntityDescription entityForName:@"Parent" inManagedObjectContext:self.managedObjectContext]];

says that you want to see the data associated with the parent entity, so you can see fetch request as a class which will hold your query and its upto you to execute that query using managedobjectContext instance method called executeRequest, now when this method will be executed it will give you an array of data. Hence i have stored the result in a mutable array (You may also take NSArray) and applied a for loop and printed some data on the console.

Step 4: Make sure you call both the methods in the method given below of you appdelegate.m file

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    // Override point for customization after app launch  
[self loadData];
[self reteriveData];

[window makeKeyAndVisible];

Once the above methods are execute you will see the output just like the one given below

Step 5: Once you see the above output make very sure that you comment the line
[self loadData]; 

else the data will be loaded twice in the database and you will see the following output.

I hope this post helped you in clearing some concepts regarding Core data in my next tutorial i will explain how to use predicate and fetch data. Feel free to comment or request a tutorial, until then Happy iCoding and have a great Day.


  1. Hey This is very useful stuff for developers like us.

  2. I can't find any documentation in the NSEntityDescription class reference that describes the method used here:

    [p1 addParentToChildObject:c1];

    It has a similar appearance to the validate{key}:error: method used when subclassing NSManagedObject, which is covered in the corresponding class reference. Can you explain this a little more?

    Otherwise, this tutorial answers a lot of questions that I had. Thanks.

  3. Aloha! I too see not docs on addParentToChildObject any where. My child parent relationships have the Parent defined as an Object in the Child.h files. I send a message [Child SetXxxx:ParentObject] after setting the Parent. All the entities are linked and use standard SetXxxx: syntax.

    This is the Parent:
    @class FacebookPhotoAlbums, StoryTitlesFollowedByUser, UserOwnedStoryTitles;

    @interface StoryUsers : NSManagedObject {
    @property (nonatomic, retain) NSString * userID;
    @property (nonatomic, retain) NSSet* StoryUsers_FacebookPhotoAlbums;
    @property (nonatomic, retain) NSSet* StoryUsers_UserOwnedStoryTitles;
    @property (nonatomic, retain) NSSet* StoryUsers_StoryTitlesFollowed;


    This is the Child:

    @class FacebookPhotosByAlbum, StoryUsers;

    @interface FacebookPhotoAlbums : NSManagedObject {
    @property (nonatomic, retain) NSNumber * albumPhotoCount;
    @property (nonatomic, retain) NSString * albumName;
    @property (nonatomic, retain) NSString * albumPhotoGraphID;
    @property (nonatomic, retain) NSData * albumPhotoData;
    @property (nonatomic, retain) NSString * albumPhotoType;
    @property (nonatomic, retain) NSString * albumID;
    @property (nonatomic, retain) NSString * albumLink;
    @property (nonatomic, retain) NSSet* FacebookAlbums_FacebookPhotos;
    @property (nonatomic, retain) StoryUsers * FacebookPhotoAlbums_StoryUsers;


    albumObject = [NSEntityDescription insertNewObjectForEntityForName:@"FacebookPhotoAlbums" inManagedObjectContext:self.context];

    [albumObject setFacebookPhotoAlbums_StoryUsers:user];

    user is allocated as a StoryUsers Object.

  4. Hi,

    You will not see any documentation for the above method thats addParentToChildObject its because that method is created by the core data framework itself and if you open your Child.h file then in that file you will see some set of methods that are provided to the developer so that he can manipulate the objects.

    Lets say in place of child and parent their was Employee and dept relationship then in that case inside the Employee.h or Dept.h their would be some methods which would be added by the core data framework depending upon the relationship so that the developer can add the employees to a department or remove the employee from a particular department,

    and in this case you will be getting a method which would be similar to the addParenttoChildObject:

    which would be somewhat like this