An iOS 7 Core Data Tutorial For Beginners

5 minutes read

An iOS 7 Core Data Tutorial For BeginnersWe will begin this tutorial by defining some of the concepts that are required to use Core Data model before providing an overview of the steps involved in working with this framework. Later we learn how to save and retrieved data from database.

 

1.  Create a Database for Coredata

Go to file-> New File -> iOS -> Coredata -> Datamodel   and create a database with name “CoreData”

core data

 

Now it’s time to create table in it, to create a table click on add entity button as shown in fig by red circle.

Core data ios 2

 

 

Core data ios 3

 

 

To add attributes in it click on ‘+’ button, it will add an attribute in list.

As in our case we have created a table with name “TableName” and two attributes column1 and column2.

 

Now we create the class object of this table, to do the same go to

 

File -> New file -> Coredata ->  NSManagedObjectSubClass and follow below steps

 

Core data ios 4

 

Now select your created database here and press next,

 

core data ios 5

 

 

After clicking on Next button you will see all the tables associated with selected database, select desired table to convert in class object from here,

(You can select multiple table together)

 

Core data ios 6

 

Congratulation now you have all the ingredients required for database operation.

 

Core data ios 7

 

 

2. Database Method

 

First of all create some properties for it in app delete

 

@property (readonly, strong, nonatomic)

NSManagedObjectContext *managedObjectContext;

 

@property (readonly, strong, nonatomic)

NSManagedObjectModel *managedObjectModel;

 

@property (readonly, strong, nonatomic)

NSPersistentStoreCoordinator

*persistentStoreCoordinator;

 

Make sure you have synthesized them before use.

 

Below are the frameworks, which we need to use coredata.  Add them in your link library first.

 

Core data ios 8

 

Now write the following methods in your AppDelegate.m

 

For more details visit here

 

#pragma mark – Core Data

 

// Returns the managed object context for the application.

// If the context doesn’t already exist, it is created and bound to the persistent store coordinator for the application.

 

– (NSManagedObjectContext *)managedObjectContext

{

    if (managedObjectContext != nil) {

        return managedObjectContext;

   }

   

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (coordinator != nil) {

        managedObjectContext = [[NSManagedObjectContext alloc] init];

        [managedObjectContext setPersistentStoreCoordinator:coordinator];

    }

    return managedObjectContext;

}

 

// Returns the managed object model for the application.

// If the model doesn’t already exist, it is created from the application’s model.

 

– (NSManagedObjectModel *)managedObjectModel

{

    if (managedObjectModel != nil) {

        return managedObjectModel;

   }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”CoreData” withExtension:@”momd”];

    managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return managedObjectModel;

}

 

// Returns the for the application.

// If the coordinator doesn’t already exist, it is created and the application’s store added to it.

 

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

   

    if (persistentStoreCoordinator != nil) {

        return persistentStoreCoordinator;

    }

   

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”CoreData.sqlite”];

   

   

    NSError *error = nil;

    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

   

    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

       

        NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

        abort();

    }

    return persistentStoreCoordinator;

   

}

 

// Returns the URL to the application’s Documents directory.

 

– (NSURL *)applicationDocumentsDirectory

{

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}

 

3.  Method to save data 

 

In our example we have a database with name “Coredata”, a table with name “TableName” and two attributes “column1” and  “column2”.

 

// Here appDelegate is the class object of applications AppDelegate

 

NSManagedObjectContext* context = [appDelegate managedObjectContext];

 

 TableName* tableObject = [NSEntityDescription insertNewObjectForEntityForName:@”TableName” inManagedObjectContext:context];

   

tableObject.column1 = @”give your value here for column1″;

 

tableObject.column2 = @”give your value here for column2″;

   

 NSError* error;

  

 BOOL isSaved = [context save:&error];

 

    if(isSaved==NO || error!=nil) {

 

        NSLog(@”Data saving Error: %@”,error.debugDescription);

 

    } else {

   

    NSLog(@”Data saved”);

 

    }

 

This will save the data in database.

 

4.  Method to retrieve data

 

NSManagedObjectContext *context = [appDelegate managedObjectContext];

    NSEntityDescription *tableEntity = [NSEntityDescription entityForName:@”TableName” inManagedObjectContext:context];

  

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];

    fetchRequest.returnsObjectsAsFaults = NO;

    [fetchRequest setEntity: tableEntity];

   

    NSError* error = nil;

   

    NSArray* logArray = [context executeFetchRequest:fetchRequest error:&error];

   

 

    if(sortedArray!=nil) {  
TableName* tableObject = [sortedArray objectAtIndex:0];

 

NSLog(@” column 1 value = %@   ,  Column 2 value = %@”, tableObject.column1, tableObject.column2);

        }

    }

 

Related Posts...

GeneralMobile AppsTechnologies

Tags: