Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 467
garethdn Avatar asked Dec 02 '22 23:12

garethdn


2 Answers

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.

like image 118
rule Avatar answered Dec 24 '22 19:12

rule


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

like image 20
tipycalFlow Avatar answered Dec 24 '22 18:12

tipycalFlow