Adding Core Data

Working on updating my hackathon application for AppStore submission I wanted to do some Core Datafication on it: that is add Core Data to an existing project that did not have the Core Data shizzle in it before.  For the hackathon I used pLists to have initial data which is one step better than just hardcoding but not scalable.  I’ve added Core Data to so many apps by now but find myself always cheating off myself and going back to my notes such that I thought it was time I centralize the four easy steps needed.  

Step 1: The Data Model
Add a Data Model to the Xcode project by going to File -> new -> Core Data -> DataModel
Make sure Entities are singular (Card instead of Cards) and start with an Uppercase.
Attributes start with a lowercase.
Make sure in the Data Model Inspector the Class is set to the Entity name.

Step 2: The Core Data Framework
Add the CoreData Framework in the project’s General Tab > Linked Frameworks & Libraries.
Add

#import <CoreData/CoreData.h>

to your .pch file under the
#ifdef __OBJC__
section

Step 3: The Managed Object Context, Managed Object Model, and Persistent Store Coordinator
Add the following properties to the AppDelegate header file:

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

Step 4: The Core Data Stack Implementation
Finally, add the Core Data Stack implementation to the app delegate .m file, changing MyDataModel to the name of the MyDataModel.xcdatamodeld file, for example if your xcdatamodeld file is named Data.xcdatamodeld then change MyDataModel to Data.

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

#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;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@&quot;MyDataModel&quot; withExtension:@&quot;momd&quot;];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
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:@&quot;YourDataBaseName.sqlite&quot;];

NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&amp;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.

Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.

If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

Lightweight migration will only work for a limited set of schema changes; consult &quot;Core Data Model Versioning and Data Migration Programming Guide&quot; for details.

*/
NSLog(@&quot;Unresolved error %@, %@&quot;, 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];
}

Now your app has Core Data and you can persist data and start using NSFetchedResultsController.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s