Adding Core Data to existing project in XCode 4

前端 未结 6 1326
一向
一向 2021-02-01 17:02

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

6条回答
  •  故里飘歌
    2021-02-01 17:48

    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 
    

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

    #ifdef __OBJC__
        #import 
        #import 
        #import 
    #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  {
      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

提交回复
热议问题