Add core data to an existing project in xcode 4

Adding core data to an existing project is not much different in Xcode 4. Just the model editor has changed a bit, here’s a tutorial showing the steps.

1.) Right click on Supporting Files and select New File.

Simulator

2.) Choose iOS > Core Data > Data Model and click Next

Simulator

3.) Name the file and click Save

Simulator

4.) A new file will show up under Supporting Files

Simulator

5.) Select it and the core data model editor will open up

Simulator

6.) Click the Add Entity button

Simulator

And name the Entity

Simulator

7.) Click the Add Attribute button

Simulator

Name the attribute and set it’s type

Simulator

8.) Select the Album entity

Simulator

9.) Select File > New File from the menu bar
Simulator

Choose Core Data > NSManagedObject subclass and hit Next

Simulator

10.) Click Create on the next screen, I just use the default location.

Simulator

11.) Add an import to the -prefix.pch file so you don’t have to import Core Data whenever you need it

#import 

#ifndef __IPHONE_3_0
#warning "This project uses features only available in iPhone SDK 3.0 and later."
#endif

#ifdef __OBJC__
    #import 
    #import 
    #import 
#endif

12.) Declare private variables for NSManagedObjectContext, NSManagedObjectModel and NSPersistentStoreCoordinator in the app delegate header file.

#import 
#import "EnterViewController.h"

@interface CoreDataTestAppDelegate : NSObject  
{

    EnterViewController *enterViewController;
    
@private
    NSManagedObjectContext *managedObjectContext;
    NSManagedObjectModel *managedObjectModel;
    NSPersistentStoreCoordinator *persistentStoreCoordinator;

    
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;

@property (nonatomic, retain) IBOutlet EnterViewController *enterViewController;

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


- (NSURL *)applicationDocumentsDirectory;
- (void)saveContext;


@end

13.) Implement the actions you declared in the header file, in the app delegate implementation file.

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

- (void)saveContext
{
    
    NSError *error = nil;
    NSManagedObjectContext *objectContext = self.managedObjectContext;
    if (objectContext != nil)
    {
        if ([objectContext hasChanges] && ![objectContext save:&error])
        {
            // add error handling here
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

14.) Implement the necessary core data methods in the app delegate implementation file

#pragma mark -
#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 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;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
    
    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 applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataTabBarTutorial.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;
}

15.) Core data is now ready to go. You’ll still need to get the managedObjectContext to which ever view controller you want to use it in and then implement the save or retrieve processes.



This entry was posted in Uncategorized, Xcode 4. Bookmark the permalink.

4 Responses to Add core data to an existing project in xcode 4

  1. Pingback: iOS gotcha’s that got me | @scottsantmyer.com

  2. Pingback: Adding Core Data for Xcode 4 Projects |Shang Liang

  3. wiralim says:

    Thanks man… great tut…

  4. test1 says:

    Some really rattling work on behalf of the owner of this web site , absolutely outstanding content .

Add Comment Register



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>