In today’s workshop, you will do the following:
- create a Core Data application called CoreDataWorkshop, which you’ll develop in throughout this tutorial series
- import the Core Data framework in the project
- set up the Core Data stack in the AppDelegate class files
- Create a Data Model file
- Create an entity in the Data Model file
Create The Core Data Application
The first step in creating an iOS application is setting up the Core Data stack. You have two options. You can let Xcode templates do it for you (Option 1) or do it yourself (Option 2).
We’ll do it ourselves, so use images in Option 2 above to create a new project.
Import The Core Data Framework
Before we can use Core Data classes and methods in CoreDataWorkshop application, you’ll have to import the Core Data framework in the project.
- Click the CoreDataWorkshop folder, then click the Build Phases tab.
- Expand the Link Binary With Libraries item, then click the + button.
- In the Choose frameworks and libraries to add window shown on your screen, enter cored in the search box. Select CoreData.framework from the list, then click the Add button.
Setup The Core Data Stack
To set up the Core Data stack, you’ll have to add these statements in the AppDelegate.h file.
#import <UIKit/UIKit.h> // Import the Core Data header file #import <CoreData/CoreData.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; // Core Data stack variables @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; // This method returns the URL to the application's Documents directory - (NSURL *)applicationDocumentsDirectory; @end
Ok, switch to the AppDelegate.m file add these statements at the top of the file, which @synthesize the Core Data Stack’s property variables.
#import "AppDelegate.h" @implementation AppDelegate @synthesize managedObjectContext = _managedObjectContext; @synthesize managedObjectModel = _managedObjectModel; @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
Now, scroll to the bottom of the file and add these methods above the @end keyboard. They setup the Core Data Stack.
#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]; } #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:@"DataSchema" withExtension:@"momd"]; _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:@"DataSchema.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]); } return _persistentStoreCoordinator; }
That’s it you’ve set up the Core Data stack in the AppDelegate class.
Create a Data Model File
Now, you need to create a Data Model file in the project. We’ll use it to create a Book entity. Now, here are the steps to create a Data Model file in the project.
- Control-click the CoreDataWorkshop folder and select New File… from the pop-up menu.
- Select Core Data under the iOS menu, in the left panel. In the right panel, select the Data Model template, then click the Next button.
- Enter DataSchema in the Save As: box, then click the Create button. Xcode will create the DataSchema.xcdatamodeld file in the Project Navigator panel.
- Click the Data Model file to load it in the Data Model editor. As you can see in Figure A below, the file is empty.
Figure A: The Data Model Editor |
Create an Entity in The Data Model File
Now that you’ve created the CoreDataSchema.xcdatamodeld file in the project, you’ll have to create an entity with three attributes in the file. An entity is basically a model of the application’s data. An attribute is a property. Follow these instructions to create an entity with three attribute in the Data Model file.
Click the Add Entity button then click the grayed-out button shown in this image.
Your screen will now look like this.
In the Data Model Inspector panel on the far right, enter Book in the Name box. Now, you need to add three attributes in the Book entity.
- Click the Add Attribute button. The editor adds an attribute called attribute in the graph. Click it to select it.
- In the Data Model Inspector panel, enter title in the Name box and select String from the Attribute Type menu.
Now repeat above steps to create these attributes for the Book entity.
Name: imageUrl | Attribute Type: String |
Name: author | Attribute Type: String |
That’s it. You are done creating the Book entity. It should like this in the Data Model editor: