开发者

Adding Core Data to existing project in XCode 4

I started off the project without Core Data and now I would like to add that functionality to my apps. How do I do this?

What additional things does XCode sets up when you actual开发者_如何学Pythonly tick the Use Core Data when you create a new project?


One trick is to just create a new empty project with Core Data support. That will give you the necessary code that you can copy over to your original project and compile.

The only gotcha is that you need to handle the Core Data header file. Xcode puts it in the precompiled header files when it generates files using the templates. So you can add the following line to your .pch file:

#import <CoreData/CoreData.h>

or you can just add it to the .m files where needed.

It works like a charm. Notice Luka's comment below about how to do it in Xcode5.


Just to expound on all the steps you actually need to perform to add Core Data to a project that previously did not have it:

Step 1: Add the Framework

Click on your app target (on the left pane its the top icon with the name of your app) then go to the 'Build Phases' tab then on 'Link Binary With Libraries', click the little '+' at the bottom then find 'CoreData.framework' and add it to your project

Then either import coredata on all the objects you need it (the non-sexy way) using:

#import <CoreData/CoreData.h>

or add the import below the common imports in your .pch file (much more sexy) like this:

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
#endif

Step 2: Add the Data Model

To add the .xcdatamodel file right click/control-click on your files in the right pane (like in a Resources folder for safe keeping) and select to Add a New File, Click the Core Data tab when selecting your file type then Click 'Data Model', give it a name and click Next and Finish and it will add it to your project. When you click on this Model object you will see the interface to add the Entities to your project with any relationships you want.

Step 3: Update App Delegate

Add these objects to AppDelegate.h

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

 - (NSURL *)applicationDocumentsDirectory; // nice to have to reference files for core data

Synthesize the previous objects in AppDelegate.m like this:

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

Then add these methods to AppDelegate.m (make sure to put the name of the model that you added in the spots shown):

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

- (NSManagedObjectContext *)managedObjectContext{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"NAMEOFYOURMODELHERE" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"NAMEOFYOURMODELHERE.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;
}

 #pragma mark - Application's Documents directory

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

Step 4: Get the Data Objects to the ViewControllers Where You Need the Data

in the ViewController.h

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

In the ViewController.m

@synthesize managedObjectContext = _managedObjectContext;

In the AppDelegate, or class where the ViewController is created set the managedObjectContext to be the same as the AppDelegate one

ViewController.managedObjectContext = self.managedObjectContext;

If you want the viewcontroller using Core Data to be a FetchedResultsController then you'll need to make sure this stuff is in your ViewController.h

@interface ViewController : UIViewController <NSFetchedResultsControllerDelegate> {
  NSFetchedResultsController *fetchedResultsController;
  NSManagedObjectContext *managedObjectContext;
}

 @property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

And this is in ViewController.m

@synthesize fetchedResultsController, managedObjectContext;

After all of that you can now use this managedObjectContext to run all the usual fetchRequests needed for CoreData goodness! Enjoy


If you want to add CoreData.framework to your project, double-click the Target in your Groups and Files list. Go to the Summary pane, and click the "+" for Linked Libraries. Choose CoreData.framework. It will then link with your project.


Xcode adds a bundle of stuff into the standard template for Core Data.

If you are not familiar with it then create a new Core Data project and push your own stuff into it rather than trying to add the infrastructure to your existing project.

Basically what you get is...

  • An empty Core Data model.
  • Init code for the Core Data stack


It's really simple to add Core Data to your project by comparing it with a new project incl. Core Data. You need to add a "Data Model" file and some methods and ivars in the AppDelegate.

Look at the Core Data Project Template in the implementation file -> "Core Data stack".


I've found the easiest way was to create a new project, with core data, delete the files in the project and drag and drop from the non-core data project to the core data project. (Main.storyboard, AppDelegate, ViewController, etc)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜