Home > Articles > Programming > General Programming/Other Languages

This chapter is from the book

Adding Core Data to an Existing Application

When you create an iOS Application project in Xcode, you can choose from various starting-point templates. Using Core Data in your project is as easy as ticking the Use Core Data check box during creation of a Master-Detail, Utility Application, or Empty Application template-based project. Adding Core Data manually is more educational, so the “Grocery Dude” project is created based on the Single View Application template, which doesn’t include Core Data. To use the Core Data Framework, you’ll need to link it to the project.

Update Grocery Dude as follows to link to the Core Data Framework:

  1. Select the Grocery Dude Target, as shown in Figure 1.2.

    Figure 1.2

    Figure 1.2 Linking the Core Data Framework

  2. Click the + found in the Linked Frameworks and Libraries section of the General tab and then link to the CoreData.framework, as shown in Figure 1.2.

Introducing Core Data Helper

If you’ve ever examined the built-in Core Data–enabled templates, you may have noticed a lot of Core Data setup is done in the application delegate. So that you may apply the approach used in this book to your own projects, Core Data will be set up using a helper class. This keeps the Core Data components modular and portable. The application delegate will be used to lazily create an instance of the CoreDataHelper class. An instance of this class will be used to do the following:

  • Initialize a managed object model
  • Initialize a persistent store coordinator with a persistent store based on the managed object model
  • Initialize a managed object context based on the persistent store coordinator

Update Grocery Dude as follows to create the CoreDataHelper class in a new Xcode group:

  1. Right-click the Grocery Dude group in Xcode and then create a new group called Generic Core Data Classes, as shown in Figure 1.3.

    Figure 1.3

    Figure 1.3 Xcode group for generic Core Data classes

  2. Select the Generic Core Data Classes group.
  3. Click File > New > File....
  4. Create a new iOS > Cocoa Touch > Objective-C class and then click Next.
  5. Set Subclass of to NSObject and Class name to CoreDataHelper and then click Next.
  6. Ensure the Grocery Dude target is ticked and then create the class in the Grocery Dude project directory.

Listing 1.1 shows new code intended for the CoreDataHelper header file.

Listing 1.1 CoreDataHelper.h

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface CoreDataHelper :NSObject

@property (nonatomic, readonly) NSManagedObjectContext       *context;
@property (nonatomic, readonly) NSManagedObjectModel         *model;
@property (nonatomic, readonly) NSPersistentStoreCoordinator *coordinator;
@property (nonatomic, readonly) NSPersistentStore            *store;

- (void)setupCoreData;
- (void)saveContext;
@end

As an Objective-C programmer, you should be familiar with the purpose of header (.h) files. CoreDataHelper.h is used to declare properties for the context, model, coordinator and the store within it. The setupCoreData method will be called once an instance of CoreDataHelper has been created in the application delegate. The saveContext method may be called whenever you would like to save changes from the managed object context to the persistent store. This method can cause interface lag if there are a lot of changes to be written to disk. It is recommended that it only be called from the applicationDidEnterBackground and applicationWillTerminate methods of AppDelegate.m—at least until background save is added in Chapter 11.

Update Grocery Dude as follows to configure the CoreDataHelper header:

  1. Replace all code in CoreDataHelper.h with the code from Listing 1.1. If you select CoreDataHelper.m, Xcode will warn that you haven’t implemented the setupCoreData and saveContext methods, which is okay for now.

Core Data Helper Implementation

The helper class will start out with four main sections. These sections are FILES, PATHS, SETUP, and SAVING. For easy navigation and readability, these areas are separated by pragma marks. As shown in Figure 1.4, the pragma mark feature of Xcode allows you to logically organize your code and automatically provides a nice menu for you to navigate with.

Figure 1.4

Figure 1.4 Pragma mark generated menu

Files

The FILES section of CoreDataHelper.m starts out with a persistent store filename stored in an NSString. When additional persistent stores are added later, this is where you’ll set their filenames. Listing 1.2 shows the code involved along with a new #define statement, which will be used in most of the classes in Grocery Dude to assist with debugging. When debug is set to 1, debug logging will be enabled for that class. Most NSLog commands will be wrapped in an if (debug == 1) statement, which will only work when debugging is enabled.

Listing 1.2 CoreDataHelper.m: FILES

#define debug 1

#pragma mark - FILES
NSString *storeFilename = @"Grocery-Dude.sqlite";

Update Grocery Dude as follows to add the FILES section:

  1. Add the code from Listing 1.2 to the bottom of CoreDataHelper.m before @end.

Paths

To persist anything to disk, Core Data needs to know where in the file system persistent store files should be located. Three separate methods help provide this information. Listing 1.3 shows the first method, which is called applicationDocumentsDirectory and returns an NSString representing the path to the application’s documents directory. You’ll also notice the first use of an if (debug==1) statement wrapping a line of code that shows what method is running. This NSLog statement is useful for seeing the order of execution of methods in the application, which is great for debugging.

Listing 1.3 CoreDataHelper.m: PATHS

#pragma mark - PATHS
- (NSString *)applicationDocumentsDirectory {
if (debug==1) {
    NSLog(@"Running %@ '%@'", self.class,NSStringFromSelector(_cmd));
}
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
}

Update Grocery Dude as follows to add the PATHS section:

  1. Add the code from Listing 1.3 to the bottom of CoreDataHelper.m before @end.

The next method, applicationStoresDirectory, appends a directory called Stores to the application’s documents directory and then returns it in an NSURL. If the Stores directory doesn’t exist, it is created as shown in Listing 1.4.

Listing 1.4 CoreDataHelper.m: applicationStoresDirectory

- (NSURL *)applicationStoresDirectory {
if (debug==1) {
    NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
}

NSURL *storesDirectory =
[[NSURL fileURLWithPath:[self applicationDocumentsDirectory]]
                                    URLByAppendingPathComponent:@"Stores"];

NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[storesDirectory path]]) {
    NSError *error = nil;
    if ([fileManager createDirectoryAtURL:storesDirectory
              withIntermediateDirectories:YES
                               attributes:nil
                                    error:&error]) {
        if (debug==1) {
            NSLog(@"Successfully created Stores directory");}
        }
        else {NSLog(@"FAILED to create Stores directory: %@", error);}
    }
    return storesDirectory;
}

Update Grocery Dude as follows to add to the PATHS section:

  1. Add the code from Listing 1.4 to the bottom of CoreDataHelper.m before @end.

The last method, which is shown in Listing 1.5, simply appends the persistent store filename to the store’s directory path. The end result is a full path to the persistent store file.

Listing 1.5 CoreDataHelper.m: storeURL

- (NSURL *)storeURL {
if (debug==1) {
    NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
}
return [[self applicationStoresDirectory]
              URLByAppendingPathComponent:storeFilename];
}

Update Grocery Dude as follows to add to the PATHS section:

  1. Add the code from Listing 1.5 to the bottom of CoreDataHelper.m before @end.

Setup

With the files and paths ready to go, it’s time to implement the three methods responsible for the initial setup of Core Data. Listing 1.6 shows the first method, called init, which runs automatically when an instance of CoreDataHelper is created.

Listing 1.6 CoreDataHelper.m: SETUP

#pragma mark - SETUP
- (id)init {
if (debug==1) {
    NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
}
    self = [super init];
    if (!self) {return nil;}

    _model = [NSManagedObjectModel mergedModelFromBundles:nil];
    _coordinator = [[NSPersistentStoreCoordinator alloc]
                            initWithManagedObjectModel:_model];
    _context = [[NSManagedObjectContext alloc]
                            initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_context setPersistentStoreCoordinator:_coordinator];
    return self;
}

The _model instance variable points to a managed object model. The managed object model is initiated from all available data model files (object graphs) found in the main bundle by calling mergedModelFromBundles and passing nil. At the moment, there are no model files in the project; however, one will be added in Chapter 2. It is possible to pass an NSArray of NSBundles here in case you wanted to merge multiple models. Usually you won’t need to worry about this.

The _coordinator instance variable points to a persistent store coordinator. It is initialized based on the _model pointer to the managed object model that has just been created. So far, the persistent store coordinator has no persistent store files because they will be added later by the setupCoreData method.

The _context instance variable points to a managed object context. It is initialized with a concurrency type that tells it to run on a “main thread” queue. You’ll need a context on the main thread whenever you have a data-driven user interface. Once the context has been initialized, it is configured to use the existing _coordinator pointer to the persistent store coordinator. Chapter 8 will demonstrate how to use multiple managed object contexts, including a background (private queue) concurrency type. For now, the main thread context will do.

Update Grocery Dude as follows to add the SETUP section:

  1. Add the code from Listing 1.6 to the bottom of CoreDataHelper.m before @end.

The next method required in the SETUP section is loadStore and is shown in Listing 1.7.

Listing 1.7 CoreDataHelper.m: loadStore

- (void)loadStore {
if (debug==1) {
NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
}
    if (_store) {return;} // Don't load store if it's already loaded
    NSError *error = nil;
    _store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType
                                        configuration:nil
                                                  URL:[self storeURL]
                                              options:nil error:&error];
    if (!_store) {NSLog(@"Failed to add store. Error: %@", error);abort();}
    else         {if (debug==1) {NSLog(@"Successfully added store: %@", _store);}}
}

The loadStore method is straightforward. Once a check for an existing _store has been performed, a pointer to a nil NSError instance is created as error. This is then used when setting the _store instance variable to capture any errors that occur during setup. If _store is nil after an attempt to set it up fails, an error is logged to the console along with the content of the error.

When the SQLite persistent store is added via addPersistentStoreWithType, a pointer to the persistent store is held in _store. The storeURL of the persistent store is the one returned by the methods created previously.

Update Grocery Dude as follows to add to the SETUP section:

  1. Add the code from Listing 1.7 to the bottom of CoreDataHelper.m before @end.

Finally, it’s time to create the setupCoreData method. With the other supporting methods in place, this is a simple task. Listing 1.8 shows the contents of this new method, which at this stage only calls loadStore. This method will be expanded later in the book as more functionality is added.

Listing 1.8 CoreDataHelper.m: setupCoreData

- (void)setupCoreData {
if (debug==1) {
    NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
}
    [self loadStore];
}

Update Grocery Dude as follows to add to the SETUP section:

  1. Add the code from Listing 1.8 to the bottom of CoreDataHelper.m before @end.

Saving

The next puzzle piece is a method called whenever you would like to save changes from the _context to the _store. This is as easy as sending the context a save: message, as shown in Listing 1.9. This method will be placed in a new SAVING section.

Listing 1.9 CoreDataHelper.m: SAVING

#pragma mark - SAVING
- (void)saveContext {
if (debug==1) {
    NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
}
    if ([_context hasChanges]) {
        NSError *error = nil;
        if ([_context save:&error]) {
            NSLog(@"_context SAVED changes to persistent store");
        } else {
            NSLog(@"Failed to save _context: %@", error);
        }
    } else {
        NSLog(@"SKIPPED _context save, there are no changes!");
    }
}

Update Grocery Dude as follows to add the SAVING section:

  1. Add the code from Listing 1.9 to the bottom of CoreDataHelper.m before @end.

The Core Data Helper is now ready to go! To use it, a new property is needed in the application delegate header. The CoreDataHelper class also needs to be imported into the application delegate header, so it knows about this new class. The bold code shown in Listing 1.10 highlights the changes required to the application delegate header.

Listing 1.10 AppDelegate.h

#import <UIKit/UIKit.h>
#import "CoreDataHelper.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong, readonly) CoreDataHelper *coreDataHelper;
@end

Update Grocery Dude as follows to add CoreDataHelper to the application delegate:

  1. Replace all code in AppDelegate.h with the code from Listing 1.10.

The next step is to update the application delegate implementation with a small method called cdh, which returns a non-nil CoreDataHelper instance. In addition, a #define debug 1 statement needs to be added for debug purposes, as shown in Listing 1.11.

Listing 1.11 AppDelegate.m: cdh

#define debug 1

- (CoreDataHelper*)cdh {
if (debug==1) {
    NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
}
    if (!_coreDataHelper) {
        _coreDataHelper = [CoreDataHelper new];
        [_coreDataHelper setupCoreData];
    }
    return _coreDataHelper;
}

Update Grocery Dude as follows to add the cdh method to the application delegate:

  1. Add the code from Listing 1.11 to AppDelegate.m on the line after @implementation AppDelegate.

The final step required is to ensure the context is saved each time the application enters the background or is terminated. This is an ideal time to save changes to disk because the user interface won’t lag during save as it is hidden. Listing 1.12 shows the code involved in saving the context.

Listing 1.12 AppDelegate.m: applicationDidEnterBackground

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[self cdh] saveContext];
}
- (void)applicationWillTerminate:(UIApplication *)application {
    [[self cdh] saveContext];
}

Update Grocery Dude as follows to ensure the context is saved when the application enters the background or is terminated:

  1. Add [[self cdh] saveContext]; to the bottom of the applicationDidEnterBackground method in AppDelegate.m.
  2. Add [[self cdh] saveContext]; to the bottom of the applicationWillTerminate method in AppDelegate.m.

Run Grocery Dude on the iOS Simulator and examine the debug log window as you press the home button (Shift+cmd.jpg+H or Hardware > Home). The log is initially blank because Core Data is set up on demand using the cdh method of the application delegate. The first time Core Data is used is during the save: that’s triggered when the application enters the background. As the application grows, the cdh method will be used earlier. Figure 1.5 shows the order of method execution once you press the home button.

Figure 1.5

Figure 1.5 The debug log window showing order of execution

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020