garethdn
garethdn

Reputation: 12351

Using core data with an existing single view application

I'm trying to learn about Core Data and am following the "Locations" tutorial from Apple. One immediate stumbling block i've come across is that I have already started constructing the application that i want to use Core Data with. It is a single view application.

What are the steps I need to take in order to utilize Core Data with this application? The tutorial says to select the checkbox "use core data for storage" when creating the project but there must be a way to enable core data after the project creation.

I'd really appreciate some help. Thanks.

Upvotes: 4

Views: 4935

Answers (6)

rule
rule

Reputation: 5677

1.) Create a View-based Application named CoreDataTutorial.

2.) Add the core data framework to the project. Right click on Frameworks, select Add > Existing Frameworks … find CoreData.frameworks and click add.

3.) Add a Data Model to the project. Right click on Resources, select Add > New File … under iOS choose Resource and then select Data Model and hit Next.

Name the file CoreDataTutorial.xcdatamodel, and hit next.

4.) Double click on the file we just created, CoreDataTutorial.xcdatamodel. This opens up the model object editor.

In the Top left pane click the + symbol to add a new Entity.

Name the entity “SomeName” by entering the name in the top right pane.

While the entity is still selected, click the + symbol in the top middle pane and choose Add Attribute.Name this Attribute “some_attribute_name” and set it to type String.

5.) Now we are going to create relationships between our two entities. Select your entity in the entity pane. Click the + symbol in the property pane and select Add Relationship. Name the relationship “creation”, set the Destination to Release and the Delete Rule to Cascade.

To do the inverse we select Release in the entity pane. Click the + symbol in the property pane and select Add Relationship. Name the relationship “creator”, set the Destination to Artist, set the Inverse to release and the Delete Rule to Cascade.

You can now close the object editor.

6.) Expand Other Sources and double click CoreDataTutorial_Prefix.pch. Add an import for CoreData.

#ifdef __OBJC__
    #import <foundation foundation.h="">
    #import <uikit uikit.h="">
    #import <coredata coredata.h="">
#endif

This saves us from having to import it into each file.

7.) Next we are going to set up the app delegate header file and then the implementation file.

First the header file. We need to create variables for our NSManagedObjectContext, the NSManagedObjectModel, and the NSPersistentStoreCoordinator.

We are also going to declare an action named applicationDocumentsDirectory, this action gets the path to the condiments directory where our data will be stored in a SQLite file. And an action that saves the context when the app quits.

Here’s what the header file looks like when we’re done. Remember we added the import statement to the CoreDataTutorial_Prefix.pch file so we don’t need to import it here.

#import <uikit uikit.h="">

@class CoreDataTutorialViewController;

@interface CoreDataTutorialAppDelegate : NSObject <uiapplicationdelegate> 
{
    UIWindow *window;
    CoreDataTutorialViewController *viewController;

@private
    NSManagedObjectContext *managedObjectContext;
    NSManagedObjectModel *managedObjectModel;
    NSPersistentStoreCoordinator *persistentStoreCoordinator;
}


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

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

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

@end

8.) If you are not using an ARC,take care about deallocating memory

9.) Implement applicationDocumentsDirectory method.

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

10.) Next, implement saveContext method:

- (void)saveContext 
{

    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) 
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&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.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
} 

11.) Finally implement your accessors methods for your variables and that's it.

Upvotes: 14

Anu
Anu

Reputation: 16

From my experience the better way to include Core Data in your project is to select a project type that has an option 'Use Core Data for storage'. You can include files from your existing project in the new one. Of course you can include Core Data manually, but it will create a lot of problems.

Upvotes: 0

Stephen Darlington
Stephen Darlington

Reputation: 52565

Honestly, if you only have a single view it's probably easiest just to create the application from scratch as the tutorial says. There are quite a few bits and pieces that you need to include and it could save you a lot of time in the long run.

However, you can do it by hand:

  • Add the Core Data framework to your project
  • Add a data model
  • Add code in your app delegate to create the managed object context (including all the error conditions)

Upvotes: 0

Phillip Mills
Phillip Mills

Reputation: 31016

If you need to see the kind of code additions that you'll need to make to access Core Data, create a dummy project that includes Core Data and look at the kind of methods that are in the app delegate to support it.

Or, you can go with a nicer approach of having your Core Data access code in its own class. A good description of that strategy can be found here: http://nachbaur.com/blog/smarter-core-data

Upvotes: 0

Jonas Schnelli
Jonas Schnelli

Reputation: 10005

Of course you can add core data support after you already started or created you app.

I would recommend you to do the following:

  • Add core data framework to your target
  • Add a object model "Add new File -> Core Data -> Data Model"
  • Create your initial object model
  • Create NSManagedObject Subclasses for all your models in your object model
  • Create a Controller (subclass NSObject) where you do a singleton / static instance (singleton)
  • In your controller add some data-layer method like "getObjectsXYZ", "saveData", etc.

  • In your existing app you can then load objects through your controller class like "[[mycontroller sharedInstance] getObjectYByName:@"some text"]"

Of course you need to dig into core data. :)

If you used to ORM's then you might look at: mogenerator vim rentsch. http://rentzsch.github.com/mogenerator/

This makes data models very very easy. I swear on that tool!

Upvotes: 2

tipycalFlow
tipycalFlow

Reputation: 7644

Go to Targets -> Build Phases -> Link Binary with libraries and add CoreData.framework. You should be good to go...

Upvotes: 2

Related Questions