31
ITP 342 Advanced Mobile App Dev Core Data

ITP 342 Advanced Mobile App Dev - University of …trinagre/itp342-20153/lectures/ITP342_CoreData.pdf– Core Data integrates well with Cocoa bindings and leverages the same technologies

Embed Size (px)

Citation preview

ITP 342 Advanced Mobile App Dev

Core Data

Persistent Data •  NSUser Defaults

–  Typically used to save app preferences •  Property List (plist) in Documents Directory

–  Data is in a dictionary or an array •  Coders and Keyed Archives

–  NSCoder and NSKeyedArchiver support saving an arbitrary object graph into a binary file

•  Direct SQLite –  Requires writing SQL queries to retrieve and save data

•  Core Data –  Provides the flexibility of working with SQLite directly

while insulating the app from the mechanics of working with the database

2

Core Data •  Core Data is a schema-driven object graph

management and persistence framework •  Fundamentally, Core Data helps you to save

model objects (in the sense of the model-view-controller design pattern) to a file and get them back again

•  Core Data is available on iOS 3.0 and later

3

Some Features of Core Data •  Modeling data objects with a visual model editor •  Automatic and manual migration tools to handle when

object schema changes •  Establishing relationships between objects (one-to-

one, one-to-many, many-to-many) •  Storing data in separate files and different file formats •  Validation of object attributes •  Querying and sorting data •  Lazy loading data •  Interacting closely with iOS table views •  Managing related object changes with commit and

undo capabilities

4

Why use Core Data? •  With Core Data, the amount of code you write to

support the model layer of your application is typically 50% to 70% smaller as measured by lines of code.

•  It provides excellent security and error-handling. •  It offers best memory scalability of any

competing solution. •  You can use templates in the Instruments

application to measure Core Data’s performance and to debug various problems.

5

What Core Data is Not •  Core Data is not a relational database or a relational

database management system (RDBMS). –  Core Data provides an infrastructure for change

management and for saving objects to and retrieving them from storage.

–  It can use SQLite as one of its persistent store types. •  Core Data is not a silver bullet.

–  Core Data does not remove the need to write code. •  Core Data does not rely on Cocoa bindings.

–  Core Data integrates well with Cocoa bindings and leverages the same technologies – and used together they can significantly reduce the amount of code you have to write – but it is possible to use Core Data without bindings.

6

Basic Architecture •  Using the Core Data framework, most of this

functionality is provided for you automatically, primarily through an object known as a managed object context (or just “context”).

•  The managed object context serves as your gateway to an underlying collection of framework objects – collectively known as the persistence stack – that mediate between the objects in your application and external data stores.

7

Basic Architecture •  Example:

Document management using Core Data

8

Managed Objects and Contexts •  You can think of a managed object context as

an intelligent scratch pad. •  When you fetch objects from a persistent store,

you bring temporary copies onto the scratch pad where they form an object graph (or a collection of object graphs).

•  You can then modify those objects however you like.

•  Unless you actually save those changes, however, the persistent store remains unaltered.

9

Managed Objects and Contexts •  Model objects that tie into in the Core Data

framework are known as managed objects. •  All managed objects must be registered with a

managed object context. •  You add objects to the graph and remove objects

from the graph using the context. •  The context tracks the changes you make, both to

individual objects' attributes and to the relationships between objects. –  By tracking changes, the context is able to provide undo

and redo support for you. –  It also ensures that if you change relationships between

objects, the integrity of the object graph is maintained.

10

Fetch Requests •  To retrieve data using a managed object context, you

create a fetch request. •  A fetch request is an object that specifies what data

you want, for example, “all Employees,” or “all Employees in the Marketing department ordered by salary, highest to lowest.”

•  A fetch request has three parts. –  Minimally it must specify the name of an entity (by

implication, you can only fetch one type of entity at a time).

–  It may contain a predicate object that specifies conditions that objects must match.

–  It may contain an array of sort descriptor objects that specifies the order in which the objects should appear.

11

Fetch Request •  An example fetch request

12

Core Data •  Core Data lets us design our data models

visually, without writing code, and stores that data model in the .xcdatamodeld file –  Xcode data model document

•  Create entities in the data model editor –  Entity refers to the description of an object

•  In code, create managed objects from those entities –  Managed object refers to actual concrete

instances of that entity created at runtime

13

Entities •  An entity is made up of 3 types of properties 1.  Attributes – hold data

–  An attribute serves the same function in a Core Data entity as an instance variable does in an Objective-C class

2.  Relationships – relationship between entities –  Relationships can be to-one and to-many

3.  Fetched properties – an alternative to a relationship

–  Fetched properties allow you to create a query that is evaluated at fetch time to see which objects belong to the relationship

14

Key-Value Coding •  Instead of using accessors and mutators,

you will use key-value coding to set properties or retrieve their existing values –  Similar to key-value coding in NSDictionary

•  When working with a managed object, the key you will use to set or retrieve a property's value is the name of the attribute you which to set

15

NSString *name = [myManagedObject valueForKey:@"name"]; ![myManagedObject setValue:@"Tommy Trojan" forKey:@"name"]; !

Backing Store •  These managed objects live in something called

a persistent store or a backing store •  By default, the app implements it as an SQLite

database stored in the app's Documents directory –  No SQL because Core Data does all the work

•  Backing stores can also be implemented as binary flat files or event stored in an XML format

•  It is possible to have multiple persistent stores •  If you're curious about how the backing store is

created and configured, take a look at the AppDelegate.m file

16

Managed Object Context •  We don't work with the persistent store directly,

instead we use a managed object context (often referred to as just a context)

•  The context manages access to the persistent store and maintains information about which properties have changed since the last time an object was save

•  Also registers all changes with the undo manager, meaning that you always have the ability to undo a single change or roll back all the way to the last time data was saved

17

Core Data Supported Data Types Data Types Objective-C Storage Integer 16 NSNumber Integer 32 NSNumber Integer 64 NSNumber Decimal NSNumber Double NSNumber Float NSNumber String NSString Boolean NSNumber Date NSDate Binary Data NSData Transformable Uses value transformer

18

Inheritance •  Core Data supports entity inheritance. •  Any entity can have one parent entitiy

specified. •  The child entitiy will inherit all the

characteristics of the parent entitiy, including attributes, validations, and indexes.

19

Core Data Project •  Project templates that allow you to select

Core Data –  Master-Detail Application –  Utility Application –  Empty Application

•  The Core Data framework will be included

20

Creating New Managed Objects •  Use insertNewObjectForEntityForName: inManagedObjectContext: factory method in a class called NSEntityDescription!

•  NSEntityDescription's job is to keep track of all the entities defined in the app's data model

•  After the call, the object exist in the context but is not yet part of the persistent store until managed object context's save: method is called

21

theName = [NSEntityDescription ! insertNewObjectForEntityForName:@"EntityName" ! inManagedObjectContext:context]; !

Retrieving Managed Objects •  To retrieve, make use of a fetch request, which

is Core Data's way of handling a predefined query

•  Optionally, you can also specify criteria for a fetch request using the NSPredicate class –  A predicate is similar to the SQL WHERE clause and

allows you to define the criteria used to determine the results of your fetch request

•  You execute the fetch request using an instance method on NSMangedObjectContext: called executeFetchRequest:error: !

22

Example

23

NSFetchRequest *request = [[NSFetchRequest alloc] init]; !NSEntityDescription *entityDescr = [NSEntityDescription! entityForName:@"EntityName" ! inManagedObjectContext:context]; ![request setEntity:entityDescr]; !!// If predicate !NSPredicate *pred = [NSPredicate predicateWithFormat: ! @"(name = %@)", nameString]; ![request setPredicate:pred]; !!NSError *error; !NSArray *objects = [context executeFetchRequest:request! error:&error]; !if (objects == nil) { ! // handle error !} !

New Project •  Create a new Empty Application •  Make sure to check the Use Core Data

checkbox

24

Data Model •  New filed called CoreData.xcdatamodeld •  Click on the Add Entity icon along the bottom

–  Rename new entity to represent the data you want to save

–  For our example, change it to Person •  Click on the Add Attribute icon along the bottom

–  Set the attribute and the type –  Add 3 attributes: color (String), name (String), number

(Integer 16) •  Click on the file to open the data model editor •  Two views (lower right corner)

–  Table mode –  Graph mode

25

Empty Application •  Create a ViewController

–  File à New à File… à Cocoa Touch (under iOS) à Objective-C class

–  Make it a subclass of UIViewController •  Create a storyboard

–  File à New à File… à User Interface (under iOS) à Storyboard

–  Name it something like MainStoryboard

26

Storyboard •  Use the Library add a View Controller •  On the Identity Inspector, set the class to

your new class (USCViewController) •  Add 2 labels •  Add 4 textfields

–  Create IBOutlets

27

Storyboard •  Under the Project Navigator, select the app

target •  Under Summary, for the Main Storyboard,

make sure to select the name of your story board (MainStoryboard)

28

Update App Delegate •  In the USCAppDelegate.m file in the application:didFinishLaunchingWithOptions: method, remove the self.window code –  Just keep return YES !

29

Update View Controller •  In the USCViewController.m file in the viewDidLoad method –  Get the context and fetch a request –  For the objects, set the textfields –  Add an observer

•  Update the applicationWillResignActive: method

30

Resources •  https://developer.apple.com/library/ios/

documentation/cocoa/conceptual/CoreData/cdProgrammingGuide.html

•  http://www.raywenderlich.com/934/core-data-on-ios-5-tutorial-getting-started

•  http://www.appcoda.com/introduction-to-core-data/

31