Add Core Data to an Application in Xcode

Who should read this Blog: User must know about Basic Concept of CoreData. Those who want to convert their non-Core data Application to a Core Data Application. Those who have some experience working with iOS Application. You must have a Sample Project to which you can convert it to CoreData Project.

So Let’s get started with Step by Step Process.

  1. First and Foremost is to Add CoreData.framework to the application directory.
  2. Now you need to add data model to your Application.

How can you do this?

Go To File-> New File->iOS->Core data->Data Model
Select Next and Give appropriate Name to your Data Model

3. Now You need to define three important property of Code Data in AppDelegate.h

1.  NSManagedObjectContext
2.  NSManagedObjectModel
3.  NSPersistentStoreCoordinator
Please refer to the Code below:

@property (nonatomic, retain, readonly) NSManagedObjectContext      *managedObjectContext;
@property (nonatomic, retain, readonly) NSManagedObjectModel        *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator             *persistentStoreCoordinator;

– (void)saveContext;
– (NSURL *)appDocumentsDirectory;

4. You need to @Synthesis all the property that you have defined in AppDelegate.m
5. Add these three methods implementations to the app delegates implementation (.m)

#pragma mark – Core Data stack

/**
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 applicationDocumentsDirectoryapplication.
*/

- (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:@"Your CoreData Model Name" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

/**
Returns the persistent store coordinator 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 appDocumentsDirectory] URLByAppendingPathComponent:@"Your CoreData Model Name .sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {

/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application’s resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult “Core Data Model Versioning and Data Migration Programming Guide” for details.
*/

NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return __persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)appDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

Do not forget to change the name of the coredate model in your application. Now you can Add Your Entity and Relationship according to your own needs. For Basic Concept of CoreData you can Refer CoreData Basic tutorial of mine.

Click here to download Sample Project code.

Written By: Pushpendra Singh , Mobile Developer, Mindfire Solutions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s