ITP 342 Advanced Mobile App Dev. Core Data

Similar documents
ios Core Data Example Application

Managed Object Model schema Persistent Store Coordinator connection Managed Object Context scratch pad

App SandBox Directory

Data Management

Core Data Programming Guide

ITP 342 Mobile App Development. Data Persistence

Mobile Application Programming. Data and Persistence

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Fall Stanford CS193p Fall 2010

Mobile Application Programming. Data and Persistence

Data IAP 2010 iphonedev.csail.mit.edu edward benson / Thursday, January 14, 2010

Data Management

Developing Applications for ios

Data Storage. Dr. Sarah Abraham

ITP 342 Mobile App Development. Data Persistence

Mobile Application Development L12: Storage & Communication

Developing Applications for ios

DOWNLOAD PDF CORE DATA PROGRAMMING GUIDE

ITP 342 Mobile App Dev. Connections

Agenda. Core Data! Next Week! Storing your Model permanently in an object-oriented database.! Multitasking! Advanced Segueing! Map Kit?

ITP 342 Mobile App Dev. Connections

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

CS193E Lecture 7. Document-based Applications NSTableView Key-Value Coding

ITP 342 Mobile App Dev. Unit Testing

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Core Data Potpourri. Paul

ITP 342 Advanced Mobile App Dev. Memory

Structuring an App Copyright 2013 Apple Inc. All Rights Reserved.

Review. Objective-C Classes, Methods, Properties, Protocols, Delegation, Memory Management

Bindings Example Exercise James Dempsey - WWDC Pre-Show Cocoa Workshop

A Mad Libs app that you will navigate through 3 UIViewControllers to add text that will be shown in a story on the fourth UIViewController.

ITP 342 Mobile App Dev. Unit Testing

ITP 342 Mobile App Dev. Fundamentals

The MVC Design Pattern

ITP 342 Mobile App Dev. Interface Builder in Xcode

Stanford CS193p. Developing Applications for ios. Winter CS193p. Winter 2017

GNUstep Database Library Introduction

Table of Contents. Table of Contents

NSObject. - (NSString *)description Provides us with a string description of the object

CSC 581: Mobile App Development Spring 2019

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Contents. iphone Training. Industry Trainers. Classroom Training Online Training ON-DEMAND Training. Read what you need

Files & Archiving. Lecture 8

S A M P L E C H A P T E R

How to Keep ERD and Data Dictionary Synchronized? Written Date : January 20, 2014

My First iphone App (for Xcode version 6.4)

I, J. Key-value observing (KVO), Label component, 32 text property, 39

Realm Mobile Database. Knoxville CocoaHeads April 2017 by Gavin Wiggins

CONFIGURING SAFE V4.0 IN THE IBM COLLABORATIVE LIFECYCLE MANAGEMENT

COMP327 Mobile Computing Session: Lecture Set 4 - Data Persistence, Core Data and Concurrency

Core Data. CS 442: Mobile App Development Michael Saelee

ITP 342 Mobile App Dev. Collection View

ADF Mobile Code Corner

Quick Web Development using JDeveloper 10g

ITP 342 Mobile App Dev. Table Views

My First iphone App. 1. Tutorial Overview

ios 101 Hands-On Challenges

Mobile Development - Lab 2

Exploring Microsoft Office Access 2007

Chapter 2. DB2 concepts

Data Storage. Mobile Application Development in ios School of EECS Washington State University Instructor: Larry Holder

InterfaceBuilder and user interfaces

lecture 8 & 9 Data Persistence + AVFoundation & Location

iphone Programming Patrick H. Madden SUNY Binghamton Computer Science Department

The Power of Predicates (Yes == NO) == NO

ITP 342 Mobile App Dev. Delegates

Building Mapping Apps for ios With Swift

Object-Oriented Programming in Objective-C

Index. btndrop function, 224, 226 btngetquote function, 246 btnpressed function, 28 btnquote method, 245. CallWeb method, 238, 240

Topics in Mobile Computing

Variable Scope The Main() Function Struct Functions Overloading Functions Using Delegates Chapter 7: Debugging and Error Handling Debugging in Visual

Integrating Game Center into a BuzzTouch 1.5 app

CS193P: HelloPoly Walkthrough

ITP 342 Mobile App Dev. Localization

ITP 342 Mobile App Dev. Table Views

Assignment III: Graphing Calculator

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

COMP327 Mobile Computing Session:

GETTING STARTED WITH CODE ON TIME Got data? Generate modern web apps in minutes. Learn to create sophisticated web apps with Code On Time application

ios Developer s Guide Version 1.0

ITP 342 Mobile App Dev. Data Types

ITP 342 Mobile App Dev

Corrections and version notes

Report Designer Report Types Table Report Multi-Column Report Label Report Parameterized Report Cross-Tab Report Drill-Down Report Chart with Static

Entrance exam - Informatics

CSCI 251: iphone Application Development

Object Persistence Design Guidelines

Introductory ios Development

Perceptive Nolij Web. Administrator Guide. Version: 6.8.x

CSC 581: Mobile App Development Spring 2018

Introducing CloudKit. A how-to guide for icloud for your Apps. Frameworks #WWDC14. Session 208 Olivier Bonnet CloudKit Client Software

Step 1: Open Xcode and select Create a new Xcode Project from the Welcome to Xcode menu.

User Interfaces. Lecture 16. Model - View - Controller. Hamza Bennani September 6, 2018

1 Build Your First App. The way to get started is to quit talking and begin doing. Walt Disney

Persistence Designer User s Guide. Version 3.4

My First Cocoa Program

Developing Applications for ios

Mastering phpmyadmiri 3.4 for

Real Application Security Administration

Assignment III: Graphing Calculator

Debugging and Profiling

Transcription:

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 modelview-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-toone, 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

Example: Document management using Core Data Basic Architecture 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 NSString *name = [mymanagedobject valueforkey:@"name"];! [mymanagedobject setvalue:@"tommy Trojan" forkey:@"name"];! 15

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 Integer 16 Integer 32 Integer 64 Decimal Double Float String Boolean Date Binary Data Transformable Objective-C Storage NSNumber NSNumber NSNumber NSNumber NSNumber NSNumber NSString NSNumber NSDate NSData 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 thename = [NSEntityDescription! insertnewobjectforentityforname:@"entityname"! inmanagedobjectcontext:context];! 21

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 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! }! 23

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:didfinishlaunchingwit hoptions: 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-dataon-ios-5-tutorial-getting-started http://www.appcoda.com/introduction-tocore-data/ 31