Tuesday 23 June 2015

Core Data in iOS


For creating a persistence storage we were previously use sqlite and perform all the basics operations on them but now a days we use core data in our applications. Using the core data in our application not only increase performance but also saves lot of time and helps in creating a robust application.

From the below tutorial we will learn how to use core data in iOS apps and also we will create a helper class that will help us to integrate it in any project within few minutes. Also we will learn how to store NSArray in core data.

Open Xcode and create a single view based application.






While creating your application make sure that use core data checkbox should be checked. You can also add the core data in the existing project at any stage.

So far we have created a project with core data and now we will learn how to create a entity (same as table in sqlite) and their attributes (same as columns in sqlite).

Open your .xcdatamodeld file and click on add entity. This will create a table let's name it as Employee. Now to store some employee informations add attributes employeeid,name and bankdetail. 




Creating relationship in Core databaseWe can use single entity for our integration purpose but to understand the relationship in core data let's create a new Entity Bank with attributes bankid,bankname.


Now change the editor style so that both the entities are visible and create a relationship (select one entity and hold and drag on other) and add the name of the relationship.



To maintain the data uniqueness specify the delete rule to cascade. So that if we delete record from one table then record of other table will be automatically gets deleted.

Now the next step is to create the NSManagedSubclass for the above entities. To create it select new file ->Core data -> Select NSManagedSubclass ->Select Entities.

So far you have created core data setup and you are ready to insert the data but before doing it there are some important terms that you should remember.


Managed Object Model - A managed object model can be refer as database schema that provides description of the entities. A managed object model is usually created by graphically using Xcode data model design tool. You have also created it above.

Managed Object Context - You can think it like a scratch pad. When we work on core data we put a temporary copy on the scratch pad and work on it. However the original copy remains unchanged until we save the changes in persistent store.This is the most important part in core data you can think it as heart of the core data because all the operations insert,update,delete,fetch,maintaing relationships are performed using managed object context.


Persistent Store Coordinator - You can treat this as a database connection. Here you specify which database to be use to store the data and where it is located.

From the above you have get all the basic understanding of core data and its creation. Now, let's start the actual journey of using it in our code. :) 




Inserting Records in Core data –

         //Get the managed object context. By default It will be created on             app delegate but in our demo we have created it on our helper class.

         NSManagedObjectContext *managedObjectContext = [[CoreDataHelper     sharedManager]managedObjectContext];
         //Create a new entity in current managed context.
         Employee *empObj = (Employee*)[NSEntityDescription        insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:managedObjectContext];
         //Set the values
         empObj.empid = [NSNumber numberWithInt:1];
         empObj.name = @"ABX";
         //Create the bank object and set all the values.
         Bank *bankObj = (Bank*)[NSEntityDescription             insertNewObjectForEntityForName:@"Bank" inManagedObjectContext:managedObjectContext];
         bankObj.bankid = [NSNumber numberWithInt:11];
         bankObj.bankname = @"AXI";
         //Set the relationship objects
         empObj.bankrelation = bankObj;
         bankObj.employeerelation = empObj;
         //save function will save all the values in the database
         NSError *error = nil;
         if (![managedObjectContext save:&error])
         {
                  NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
         }

To Fetch the Entity from Core Data


         
//Create a NSFetchRequest object
         NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
         //Get the specified entity
         NSEntityDescription *entity = [NSEntityDescription
                  entityForName:@"Employee"       inManagedObjectContext:managedObjectContext];
         NSError *error =nil;
         //Set the entity in the fetch request
         [fetchRequest setEntity:entity];
         //Execute the fetch request which will give the array of stored data
         NSArray *fetchedObjects = [managedObjectContext                                                       executeFetchRequest:fetchRequest error:&error];
         for (Employee *emp in fetchedObjects)
         {
                  NSLog(@"Name: %@",emp.name);
                  Bank *bank = emp.bankrelation;
                  NSLog(@"Bank name: %@",bank.bankname);
         }
To get data in the sorting order create a NSSortDescriptor and set it on fetch request.

          NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:YES];
         NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
         [fetchRequest setSortDescriptors:sortDescriptors];
Further if you want to get data on specific condition (same as applying where clause in sqlite) create the NSPredicate and set it on fetchRequest Object.

         [ fetchRequest setPredicate:predicate];


To Delete the Entity from Core Data


         
//Pass the object that you want to delete in delete Object function
         [managedObjectContext deleteObject:entityToDelete];
         //Save the context so that changes gets saved on the database
         if (![managedObjectContext save:&error])
         {
              NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
         }

To Update Records in Core data


Updating a record in core data is very simple. Fetch the old record from the database and set the new value of attribute that you want to update and call the save function. That's all you have successfully updated your record.


Storing NSArray in Core Data


To store a NSArray in core data is a very easy task. Core data provides a attribute type called
transformable. You have to simply create a entity of type transformable and assign the NSArray object to this attribute when you save your data. Core data internally use NSValueTransformer to convert it in NSData to save it.

Watching Raw SQL Statement

To get the raw sql query that is executed behind the operation can be get by adding com.apple.CoreData.SQLDebug 1 under arguments tab in Run Scheme.
EditScheme -> Select Run Scheme -> Select Arguments Tab -> Add 
com.apple.CoreData.SQLDebug 1


From the above you have learn how to use core data. For easy integration of it we have created the CoreDataHelper classes that you can directly integrate in your project.



Here is 
sampleproject and Helper Class with all the code of the above tutorial.

If you face any issue or suggestions, please leave your comment.



 

6 comments:


  1. Nice Blog, When i was read this blog i learnt new things & its truly have well stuff related to developing technology, Thank you for sharing this blog.
    iphone training courses in bangalore
    iphone training courses in bangalore

    ReplyDelete