Top Banner
An Intertech Course Introduction to Core Data for iOS Jason Shapiro, Intertech
42

Introduction to Core Data - Jason Shapiro

May 10, 2015

Download

Documents

Mobile March

Jason Shapiro's 3/21 presentation at Mobile March 2013
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to Core Data - Jason Shapiro

An Intertech Course

Introduction to Core Data for iOS

Jason Shapiro, Intertech

Page 2: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 2

Award-Winning Training and Consulting.

Visit www.Intertech.com for complete details.

Page 3: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 3

Intertech offers

Mobile Training On:

• Android• HTML5• iOS • Java ME• jQuery• Windows Phone

Visit www.Intertech.com for complete course schedule.

Page 4: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 4

Stop by Intertech’s booth for a chance to win FREE Training.

Or go to bit.ly.com/intertech-login

Page 5: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 5

Welcome• Jason S. Shapiro – [email protected]

• Intertech Blog: http://www.intertech.com/blog• My LinkedIn Profile - http://linkedin.com/in/jshapiro

• ~19 Years Professional Software Development and Architecture Experience

• Master of Science in Software Engineering (2004)

• Sun Certified Java Programmer (2001) & Web Component Developer (2004)

• Scrum Alliance Certified ScrumMaster

from page: 3

Page 6: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 6

Welcome• About this Presentation:

• This is an intermediate level presentation. • The assumption is that you are currently actively programming in iOS, and are

familiar with Objective-C and Xcode.• Slides are at http://www.intertech.com/downloads/coredata.pdf

from page: 3

Page 7: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 7

Options for Persistence in iOS• Core Data is used for data persistence.• So, what is data persistence?

• The act of preserving data in non-volatile storage.• Simply put: the ability to retain information after a program has shut down.

• Special considerations for iOS• Limited Memory – the number of active apps reduces the amount of memory

available, and affects performance.• No “Backing Store” or Automatic Paging – memory is released, not saved, when

the device hits its limits. In worst-case scenarios, an app will receive a warning to release memory.

• Data Sharing Among Devices – users often own multiple devices they’d like to share state between.

from page: 4

Page 8: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 8

Options for Persistence in iOS Cont.• Common options for data persistence in iOS

Type Description

File System Saves data to a non-volatile area of memory on the device (binary, plist, etc)

Networked Data Store

Transfer data to an external resource. Typical options here are a RESTful Web Service or iCloud.

SQLite C-based API & relational database.

Core Data Provides an object oriented way or managing and persisting data.

from page: 4

Page 9: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 9

Options for Persistence in iOS Cont.• What is Core Data?

• An Objective-C API and modeling tool that is used to manage object-graphs.• Available for free with Xcode.• Typically sits on top of SQLite, though other data stores can be used.

• Allows you to treat persistence in an object oriented manner (similar to ORM frameworks).

• Lazy loads data with “faults.”

from page: 5

Page 10: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 10

Options for Persistence in iOS Cont.• Handles undo/redo operations.• Provides an infrastructure for data validation.

from page: 5

Page 11: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 11

Core Data Architecture• There are 5 core classes that are used in most operations with Core Data.

• Your code will typically call the methods and properties of Managed Objects and The Managed Object Context.• Although you will create the Managed Object Model, Persistent Store Coordinator,

and Persistent Store, these objects will be invoked indirectly by way of the Managed Object Context.

from page: 6

Page 12: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 12

Core Data Architecture Cont.• Managed Objects (NSManagedObject or subclass) represents

the model of your apps.• These are the objects that represent data you want to persist. • For example: Employee, Customer, Order, etc.• The actual code for each class is generated for you based on the

model (though you may modify it if necessary).• Because this is an object-graph management tool, changes in one

class can affect another. The modeling tool classifies these as “Relationships.”

from page: 6

Page 13: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 13

Core Data Architecture Cont.• The Managed Object Context (NSManagedObjectContext) puts the “managed”

in Managed Objects.• Whenever you create, delete, or fetch a managed object, the

NSManagedObjectContext is involved. • This is typically as low of a Core Data API call you’ll need to make in your

applications.

from page: 7

Page 14: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 14

Core Data Architecture Cont.• The Persistent Store Coordinator

(NSPersistentStoreCoordinator) & NSManagedObjectModel work with the Persistent Store to manage the lower level details of persistence.• A Persistent Store represents the physical file. This could be a

SQL Database, a binary file, etc.• In most iOS apps, you will typically have one persistent store,

though it is possible to have more.• In those cases, a single NSPersistentStoreCoordinator manages

all persistent stores.• The coordinator uses the NSManagedObjectModel to determine

how objects should be mapped to the Persistent Store.• It is very rare for you to need to invoke methods directly on

these three objects.

from page: 7

Page 15: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 15

Schema Design in Xcode• Before data can be persisted, it must be modeled.

• Modeling describes the composition and relationships within an object-graph.• A model is created as an *.xcdatamodeld file and constructed through a special

model editor in Xcode.• Xcode compiles this into a *.momd file, which in turn is encapsulated in the

NSManagedObjectModel.

from page: 8

Page 16: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 16

Schema Design in Xcode Cont.• A single model class is notated as an Entity.

• An entity may contain “Attributes” which are manifested as properties.• Relationships between other classes may be defined (one to many, many to one,

many to many), which are also manifested as properties.

from page: 10

Page 17: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 17

Demo: Creating an Object Modelfrom page: 10

Page 18: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 18

Generating Model Classes• Once a model has been created, it is possible to simply use each entity as an

NSManagedObject in your app.• The way these are fetched from Core Data is described in an upcoming section.• Attributes can be reached through Objective C’s “key-value coding” capabilities. • In short, key-value coding means that a String can be passed in, and resolved as a

property.• To read @property (nonatomic, strong) NSString *fullName:

• To set that property:

[obj valueForKey:@"fullName"];

[obj setValue:@"Jason Shapiro" forKey:@"fullName"];

from page: 12

Page 19: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 19

Generating Model Classes Cont.• While this is a valid strategy, it is easier to work with actual model objects.

• Having a “Customer” and “Order” objects is easier to understand compared to having multiple “NSManagedObjects”

• This allows you to use standard property notation for accessing attributes.• In addition, you can create extra methods for additional model behavior.

• Generating model objects is a simple process.• Select each of the entities in your model.• In the top menu, select Editor -> Create NSManagedObject Subclass...

from page: 12

Page 20: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 20

Demo: Generating NSManagedObject Subclassesfrom page: 13

Page 21: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 21

Basic App Configuration• Once the model has been completed, some basic infrastructure must be added

to the app.• Add the “CoreData.framework” to your app.• Next, create and configure a NSManagedObjectContext.• This object is used directly, and passed to other helper classes, for the purpose of

interacting with the persistence tier.

• There are two common strategies for the construction of the NSManagedObjectContext.• This seminar focuses on the most common strategy: creating and configuring the

basic Core Data stack (NSManagedObjectModel, NSPersistentStoreCoordinator, and NSManagedObjectContext).

• A more recent strategy involves using a UIManagedDocument.• Although this isn’t covered here, note that this strategy includes strong integration

with iCloud and includes features such as auto-saving.

from page: 14

Page 22: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 22

Basic App Configuration Cont.• There are three steps for configuring the NSManagedObjectContext

• All of the following code is typically added to the App Delegate:

1. The data model is automatically compiled into a *.momd file. Load this into a NSManagedObjectModel object:

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CustomerManagementSystem" withExtension:@"momd"];NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

from page: 14

Page 23: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 23

Basic App Configuration Cont.

2. Create a NSPersistentStoreCoordinator, configured with the NSManagedObjectModel.

NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CustomerManagementSystem.sqlite"]; NSError *error = nil; if (![coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]);}

from page: 15

Page 24: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 24

Basic App Configuration Cont.

3. Create the NSManagedObjectContext, configured with the NSPersistentStoreCoordinator.

from page: 15

NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];context.persistentStoreCoordinator = coordinator;

Page 25: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 25

Basic App Configuration Cont.from page: 15

The fully configured NSManagedObjectContext can be pictured like this:

Page 26: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 26

Demo: Using the “Empty Application” Project Templatefrom page: 16

Page 27: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 27

CRUD Operations• Now that the NSManagedObjectContext is available, CRUD operations may be

applied to Managed Objects.• CRUD is Create, Read, Update, and Delete.• The standard pattern in iOS is to use the NSManagedObjectContext, or a helper

class that is configured with it, to execute CRUD functionality.• All CRUD operations happen in memory.• In order to persist any changes, the NSManagedObjectContext must receive a “save”

message.

from page: 17

Page 28: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 28

CRUD Operations Cont.• Managed Objects are not created through standard alloc/init. calls.

• Instead an Entity Description (NSEntityDescription), which is configured with the NSManagedObjectContext, is used for object creation.

• Next, standard property calls are used to configure the object’s attributes.

• Object relationships should use one of the Managed Object’s generated methods.

Customer *customer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:self.context];

customer.fullName = @”Jason Shapiro”;

Order *order = [NSEntityDescription insertNewObjectForEntityForName:@"Order" inManagedObjectContext:self.managedObjectContext]; // Configure Order code would be placed here... [customer addOrdersObject:order];

from page: 17

Page 29: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 29

CRUD Operations Cont.

• Finally, the NSManagedObjectContext is told to save any “dirty” objects it is managing.

from page: 17

NSError *error;[self.context save:&error];if( error ){ NSLog(@"Error: %@", error);}

Page 30: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 30

CRUD Operations Cont.• Updating a Managed Object is as simple as making changes to its properties

and/or relationships.• Once a change has been detected, it will be persisted upon the next save action

NSError *error;[self.context save:&error];if( error ){ NSLog(@"Error: %@", error);}

from page: 18

Page 31: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 31

CRUD Operations Cont.• Delete

• While deleting an object is a simple method call, it does take a bit of planning.• In the Data Model, each relationship contains a “Delete Rule.”• The four available rules are:

Delete Rule

Description

No Action

Don’t delete the related objects.

Nullify Don’t delete the related objects, but set their inverse properties to nil.

Cascade Delete all related objects (be careful!)

Deny If there are any related objects still in existence, deny the deletion request.

from page: 18

Page 32: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 32

CRUD Operations Cont.• Once the delete rule is set appropriately, the delete action is very simple:

[self.managedObjectContext deleteObject:customer]; NSError *error;[self.managedObjectContext save:&error];if( error ){ NSLog(@"Error: %@", error);}

from page: 18

Page 33: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 33

CRUD Operations Cont.• A Read action uses a few different objects to construct its request.

• NSFetchRequest – The object which encapsulates the entire request, including the batch size.

• NSEntityDescription – Specifies the entity type to retrieve.• NSSortDescriptor – Determines one or more attributes to sort on and whether or

not the order is ascending or descending.• NSPredicate – Optional. Similar to a “where” clause in SQL.• NSManagedObjectContext – Executes the fetch request.

from page: 19

Page 34: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 34

CRUD Operations Cont.• This first example retrieves all customer objects, sorting them by the

Customer’s fullName in an ascending order.• All of the related Order managed objects are “faulted.”• This means that a mock object is substituted during the initial load. As a

relationship path is followed with the ‘.’ operator, the real object is retrieved from the data store. i.e. customer.orders[0].productId.

from page: 19

Page 35: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 35

CRUD Operations Cont.NSFetchRequest *request = [[NSFetchRequest alloc] init];request.fetchBatchSize = 100; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Customer" inManagedObjectContext:self.managedObjectContext];[request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES];NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];[request setSortDescriptors:sortDescriptors]; NSError *error = nil;NSArray *customers = [self.managedObjectContext executeFetchRequest:request error:&error];if (error) { NSLog(@"Error: %@", error);}

from page: 19

Page 36: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 36

CRUD Operations Cont.• Predicates have a unique syntax, which is described in Apple’s Predicate

Programming Guide.• Applying a predicate involves creating an NSPredicate object and sending

it to the NSFetchRequest.

NSString *attribute = @"fullName";NSString *myName = @"Jason Shapiro";NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", attribute, myName];[request setPredicate:predicate];

from page: 20

Page 37: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 37

Fetched Results Controller• Core Data provides an object to help manage data being displayed in a Table

or Collection View: NSFetchedResultsController.• Doesn’t provide direct data binding, but does provide methods and properties that

answer data source questions.• In addition, it sends events to a delegate when the data has been updating, allowing

you to easily update the view.

from page: 21

Page 38: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 38

Fetched Results Controller Cont.• Using a NSFetchedResultsController follows the same steps as a regular fetch

request.• The only difference is that instead of passing the NSFetchRequest to the

NSManagedObjectContext, both of these objects are passed to an NSFetchedResultsController.

• The init method includes a parameter for a “sectionNameKeyPath” which specifies the path to a property that specifies the name of the section it should be placed in.

• There is also a “cacheName” which is an arbitrary NSString to enable/use a cache.

self.fetchedRC = [[NSFetchedResultsController alloc] initWithFetchRequest:req managedObjectContext:self.context sectionNameKeyPath:nil cacheName:nil];

from page: 21

Page 39: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 39

Fetched Results Controller Cont.• To receive events when the managed data has changed (such as creating or

deleting an object), execute the following three steps:• Conform to the NSFetchedResultsControllerDelegate protocol.• Set yourself as the NSFetchedResultsController’s delegate• Implement the

controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: method.

from page: 21

Page 40: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 40

Demo: Using a Fetched Results Controllerfrom page: 21

Page 41: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 41

Recap• What we covered:

• Options for Persistence in iOS• Core Data Architecture• Schema Design in Xcode• Generating Model Classes• Basic App Configuration• CRUD Operations• Fetched Results Controller

• Q&A

from page: 23

Page 42: Introduction to Core Data - Jason Shapiro

Introduction to Core Data for iOS

Copyright © Intertech, Inc. • www.Intertech.com • 800-866-9884 Slide 42

Suggested Resources• Core Data Model Versioning and Data Migration Programming Guide –

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/Introduction.html

• Core Data Programming Guide – http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html

• Core Data Tutorial for iOS - http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/iPhoneCoreData01/Introduction/Introduction.html

• Dr. Dobb’s Understanding Core Data on iOS - http://www.drdobbs.com/database/understanding-core-data-on-ios/240004648

• Predicates Programming Guide - https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/predicates.html

• The Core iOS 6 Developer’s Cookbook by Erica Sadun

from page: 24