core data for ios: developing data-driven applications for...

48

Upload: others

Post on 09-Jul-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Core Datafor iOSDeveloping Data-Driven Applications forthe iPad®, iPhone®, and iPod touch®

Tim IstedTom Harrington

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco

New York • Toronto • Montreal • London • Munich • Paris • Madrid

Cape Town • Sydney • Tokyo • Singapore • Mexico City

Many of the designations used by manufacturers and sellers to distinguish theirproducts are claimed as trademarks. Where those designations appear in thisbook, and the publisher was aware of a trademark claim, the designations havebeen printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, butmake no expressed or implied warranty of any kind and assume no responsibilityfor errors or omissions. No liability is assumed for incidental or consequentialdamages in connection with or arising out of the use of the information orprograms contained herein.

The publisher offers excellent discounts on this book when ordered in quantity forbulk purchases or special sales, which may include electronic versions and/orcustom covers and content particular to your business, training goals, marketingfocus, and branding interests. For more information, please contact:

U.S. Corporate and Government Sales(800) [email protected]

For sales outside the United States please contact:

International [email protected]

Visit us on the Web: informit.com/aw

Library of Congress Cataloging-in-Publication Data is on file.

Copyright © 2011 Pearson Education, Inc.

All rights reserved. Printed in the United States of America. This publication isprotected by copyright, and permission must be obtained from the publisher prior toany prohibited reproduction, storage in a retrieval system, or transmission in anyform or by any means, electronic, mechanical, photocopying, recording, or likewise.For information regarding permissions, write to:

Pearson Education, IncRights and Contracts Department501 Boylston Street, Suite 900Boston, MA 02116Fax (617) 671 3447

ISBN-13: 978-0-321-67042-7

ISBN-10: 0-321-67042-6

Text printed in the United States on recycled paper at R.R. Donnelley inCrawfordsville, Indiana

First printing June 2011

Editor-in-ChiefMark Taub

Senior Acquisitions EditorChuck Toporek

Development EditorChuck Toporek

Managing EditorKristy Hart

Project EditorAndy Beaster

IndexerLarry Sweazy

ProofreaderJennifer Gallant

Technical ReviewersJim CorreiaRobert McGovernMike Swan

Publishing CoordinatorOlivia Basegio

Interior DesignerGary Adair

Cover DesignerChuti Prasertsith

CompositorGloria Schurick

iii

Part I Introduction

1 An Overview of Core Data on iOS Devices 3

A Little History................................................................................................3The Birth of Core Data ..........................................................................4

Why Use Core Data on iOS? ..........................................................................4Relationship Management ....................................................................4Managed Objects and Data Validation .................................................5Undo and State Management................................................................5

Core Data iOS and Desktop Differences.........................................................5The Fetched Results Controller .............................................................6

Core Data Case Studies ...................................................................................6MoneyWell for iPhone ..........................................................................6Calcuccino .............................................................................................7Associated Press .....................................................................................8

2 A Core Data Primer 9

Persisting Objects to Disk ...............................................................................9The Core Data Approach ..............................................................................10

Entities and Managed Objects.............................................................10Relationships........................................................................................11Managed Object Contexts ...................................................................12Fetching Objects ..................................................................................14Faulting and Uniquing ........................................................................14Persistent Stores and Persistent Store Coordinators ...........................15

Examining the Xcode Core Data Templates ................................................15The Navigation-Based Project Template..............................................16The Data Modeler ................................................................................16Setting up the Core Data Stack ...........................................................17Running the Application.....................................................................20A Quick Look at the RootViewController Code .................................20

Summary .......................................................................................................21

Table of Contents

iv

3 Modeling Your Data 23

Managed Objects and Entities ......................................................................23Dividing Your Data into Entities ..................................................................24

Core Data in Model-Object Terms ......................................................24Data Normalization .............................................................................25Storing Binary Data .............................................................................27

Working with Xcode’s Data Modeler ...........................................................28Creating Entities ..................................................................................29Creating Properties ..............................................................................31Creating Relationships ........................................................................35

Summary .......................................................................................................37

Part II Working with Core Data

4 Basic Storing and Fetching 41

Creating New Managed Objects ...................................................................41Saving the Context ..............................................................................42

Fetching Saved Managed Objects .................................................................44Deleting Managed Objects............................................................................45Working with Table Views ............................................................................46

The Random Dates Application Project ..............................................47The Random Dates Data Model ..........................................................48Basic RootViewController Behavior ....................................................49Fetching the Random Date Objects ....................................................51Displaying the RandomDate Objects ..................................................52Deleting the RandomDate Objects......................................................54

Custom Managed Object Sub-Classes...........................................................54Creating and Setting a Custom Class for a Managed Object .............56

Summary .......................................................................................................60

5 Using NSFetchedResultsController 61

Introducing NSFetchedResultsController .....................................................62Creating an NSFetchedResultsController .....................................................62Supplying Information to Table Views.........................................................64

The Number of Sections and Rows .....................................................65Returning the Cell for an Index Path .................................................67Returning Information about Sections ...............................................68Handling Underlying Data Changes...................................................69Caching Information...........................................................................72

Using an NSFetchedResultsController in the Random Dates Application..73Subclassing NSFetchedResultsController ............................................80

Summary .......................................................................................................85

Core Data for iOS

vContents

6 Working with Managed Objects 87

Basic Managed Object Subclass Files ............................................................87Creating the Random People Project ..................................................88Managed Object Class Interfaces.........................................................89Managed Object Class Implementations ............................................90

Configuring the Random People Application..............................................93Displaying the Information.................................................................95

Data Validation .............................................................................................99Validating Individual Properties..........................................................99Validation Based on Other Properties ...............................................101Validation Prior to Deletion ..............................................................104Fixing the Random People Application ............................................105

Working with Transient Attributes.............................................................105Modifying the Data Model................................................................106Adding to the AWPerson Interface and Implementation.................106Adding a Getter Method for the Transient Property ........................108Adding a Setter Method for the Transient Property .........................110Using the UIColor Property...............................................................111

Working with Transformable Attributes.....................................................113The Managed Object Lifecycle ...................................................................114

Initializing Non-persistent Properties ...............................................114Summary .....................................................................................................116

7 Working with Predicates 117

Predicate Basics ...........................................................................................117Creating Predicates Using Format Strings.........................................118Predicate Variables .............................................................................120Predicate Comparison Operators.......................................................122Key Paths............................................................................................123

Comparing Strings ......................................................................................124Compound Predicates.................................................................................126

NSCompoundPredicate .....................................................................128Sets and Relationships ................................................................................129Examining SQL Queries ..............................................................................130Adding a Search Display Controller ...........................................................130

Setting a Fetch Predicate ...................................................................132Modifying the Search Predicate.........................................................136Adding a Search Scope Bar Filter.......................................................139

Summary .....................................................................................................141

vi Core Data for iOS

8 Migration and Versioning 143

The Migration Problem...............................................................................143Changing the Data Model.................................................................144

Multiple Data Model Versions and Lightweight Migration.......................145Creating Data Model Versions...........................................................145Enabling Lightweight Migration .......................................................146

Renaming Entities and Attributes ..............................................................148Supplying Renaming Identifiers........................................................150Keeping Track of Multiple Versions ..................................................151

Mapping Models .........................................................................................152Custom Entity Migration Policies ..............................................................156Summary .....................................................................................................160

9 Working with Multiple View Controllers and Undo 163

Editing Managed Objects............................................................................163Keeping Track of the Managed Object to Edit ..................................164Updating a Managed Object’s Properties ..........................................168Validating Managed Objects .............................................................171

Working with Undo....................................................................................174Multiple Managed Object Contexts ...........................................................175

Merging Changes from Other Managed Object Contexts................178Changing Managed Object Values Whenever the Control Values

Change.............................................................................................179Resetting a Managed Object Context ...............................................181Using the Editor Controller to Add New Objects .............................182

Summary .....................................................................................................183

Part III Building a Simple Core Data Application

10 Sample Application: Note Collector 187

The Note Collector Application .................................................................187Creating the Note Collector Project..................................................188

The Application Data Model ......................................................................188Modeling an Abstract Entity .............................................................189Modeling Sub-entities........................................................................189Creating Managed Object Class Files ................................................190

Configuring the RootViewController.........................................................192Displaying the Contents of a Collection....................................................195

Keeping Track of the Collection to be Displayed .............................196Examining the Contents of a Raw Data File.....................................200

viiContents

Setting and Editing an Item Name.............................................................202Creating the New View Controller....................................................203

Displaying and Editing Notes.....................................................................210Supplying a Pre-Populated Data Store........................................................217

Working with a Data Store in the Application Bundle.....................217Summary .....................................................................................................219

Part IV Optimizing and Troubleshooting

11 Optimizing for iOS Performance and Memory Requirements 223

Performance, Optimization, and Speed .....................................................224Data Store Types..........................................................................................224

Binary and Memory Data Stores .......................................................225SQLite Data Store...............................................................................225Monitoring SQLite Stores ..................................................................225

Optimizing Fetching...................................................................................230Setting Fetch Limits ...........................................................................230Optimizing Predicates........................................................................231Pre-Fetching Relationships ................................................................233Pre-Fetching Any Object....................................................................234Pre-Loading Property Values .............................................................235NSFetchedResultsController and Sections ........................................235

Managing Faulting ......................................................................................235“Safe” Fault-Free Methods .................................................................236Preventing Property Loading.............................................................237Batch Faulting....................................................................................237Re-faulting Objects ............................................................................237

Managing BLOBs.........................................................................................238Putting BLOBs in the Entity That Uses Them ..................................239Putting BLOBs in a Separate Entity...................................................240Putting BLOBs in External Files ........................................................242

Monitoring Core Data with Instruments ...................................................245When Not to Use Core Data.......................................................................248Other Memory Management Tips ..............................................................248

Don’t Use an Undo Manager If You Don’t Need It ..........................249Resetting the Managed Object Context ............................................249

Summary .....................................................................................................249

12 Troubleshooting Core Data 251

Your First Core Data Error ..........................................................................251The Missing Model ............................................................................254Classes Not Found?............................................................................255

viii Core Data for iOS

Core Data Threading Issues ........................................................................257Basics of Core Data Multithreading ..................................................257Coordinating Data Between Threads ................................................258When Threads Collide, or Handling Data Conflicts ........................260Danger! Temporary ID! ......................................................................264

Problems Using Managed Objects ..............................................................265Crashing When Setting Property Values...........................................265If Custom Accessor Methods Aren’t Called ......................................266Managed Object Invalidated .............................................................267Faults That Can’t Be Fulfilled ............................................................268

Problems Fetching Objects .........................................................................269Trouble Sorting Data During Fetches ................................................269Fetch Results Not Showing Recent Changes.....................................270

Summary .....................................................................................................270

Index 271

Preface

We live in a data-driven world. We consume social data, like email, Twitter, and Facebook,business data, like share prices, financial forecasts, and bank accounts, and occasionallywe might have a little fun with the more recreational side to life, like brainteasers, orgames involving squawking birds and mock air traffic control, where we expect to be ableto track our progress and rejoice when we beat our previous high scores.

As mobile devices increase in performance, capacity, and capability, we place ever-increas-ing demands on our phones or tablet devices to consume, save, fetch, search and displayour data. Consumers buy iPhones, iPod touches and iPads with storage capacities unheardof in handheld or even desktop devices only a few years ago, and they expect to fill thosecapacities either with media, or with applications and data.

It’s increasingly difficult to imagine an application with any non-trivial functionality thatdoesn’t maintain at least some kind of data store. Even if a Twitter client maintains only atemporary store of downloaded tweets, it will at least need to keep permanent track of oneor more Twitter account usernames for timeline refresh; calculator applications havepersistent memories for calculated values, or store a history of previous calculations; and,in order for us to feel a sense of achievement, games store a history of high scores, as wellas a state of play so that we can return immediately to our gun-slinging 3D shoot-‘em-upjust as soon as we finish our FaceTime chat.

For us mobile app developers, the demands are high. Not only do users expect our apps tostore data as efficiently as possible, they expect their applications to run quickly,smoothly, and without crashing. Given the relatively limited runtime memory capacitiesof these mobile devices, dealing with persistent data can quickly become a nightmare.Mobile devices also introduce the issue of power management, which is rarely a concernwhen writing software for desktop computers. An app that eats batteries will not please itsusers.

When the iPhone SDK first launched, developers were left to fend for themselves when itcame to data access. Data persistence was possible only via basic file storage, or throughdirect access to a SQLite database. SQLite can certainly help out with the limited runtimememory problems, but generally requires developers to fashion their own persistence layerto interact with model objects and generate the underlying SQL commands necessary tosave and restore plain data.

Core Data changes all that. From version 3.0 of the iPhone SDK (renamed to iOS as ofversion 4.0) onwards, Apple provides us with a ready-made data persistence layer. Wedefine a schema for the model objects we want to store, then leave Core Data to figure outwhat to do to persist our model data to disk. We don’t have to worry about low-level SQLcommands, or the memory meltdowns involved when loading 1GB of data from a singlefile. Instead we work with a “data store,” a term that is intentionally vague since details ofmanaging data files are abstracted away. Developers are free to work with their objects andleave the file management to the framework.

x Core Data for iOS

If Core Animation is the sexy framework for views, we now have an equally sexy (thoughpossibly less visually glamorous) framework to help us with our model. By taking awaymuch of the drudgery of data persistence, we’re left with more time to work on thefeatures and functionality unique to our applications.

Core Data can be the perfect answer to many data-related prayers, but it comes with asteep initial learning curve. Because of its ability to work easily with a SQLite database forits storage, it’s often mistaken for a database itself and, although this is inaccurate, itcertainly helps to have a basic understanding of general database terms and techniques.

Although the number of Core Data classes is relatively small, it’s necessary to make use ofmost of them before you can do anything at all with the framework. It’s hard to under-stand terms like “managed object context” before you understand “managed object,” or“persistent store,” but in order to make use of a managed object, you need a managedobject context, and a persistent store. Getting over the initial leap of faith in a basic CoreData stack can seem a sizeable obstacle in making use of the framework.

This book teaches Core Data from the ground up. You’ll learn about these primary classesin the framework, seeing how they interact to provide amazing functionality with verylittle configuration and tweaking. You’ll find out how to store and fetch data, look at bestpractices for providing data to the staple view of many data-driven apps, UITableView, anddiscover how easy it can be to perform data validation to ensure data integrity. Finally,you’ll look at ways to troubleshoot your Core Data applications, or enhance data-relatedperformance bottlenecks.

By the end of the book, you’ll have a thorough understanding of the framework and itsclasses, and probably be left wondering how you ever managed without it.

Audience for This Book

Aimed at intermediate to advanced iOS developers, the book assumes that you have areasonable working knowledge of programming iOS applications. In particular, you shouldbe comfortable working with Apple’s basic developer tools (Xcode), the Objective-Clanguage, and the Cocoa Touch framework.

It is not assumed that you have already worked with Core Data on the desktop, althoughthe vast majority of the information included in this book applies to Core Data in general,both on iOS devices, and under Mac OS X (10.4 or later). Once you’ve mastered Core Dataon iOS, you’ll be able to use the same tools (Xcode’s data modeler) and much of the samecode (with the exception of NSFetchedResultsController, which is iOS-only) to buildCore Data applications on the desktop.

xiPreface

Who Should Read this Book

If you write iOS applications, you’ll probably have data persistence needs. If you need towork with anything other than the most trivial data storage, you’ll likely find it easier towork with Core Data than to create your own file-based or low-level SQLite-based persis-tence layer. If you need to work with Core Data, you should read this book.

If you’ve never used Core Data before, this book will teach you what you need to know toget started. Once you’ve mastered the fundamentals of the framework, including the iOS-specific NSFetchedResultsController, and walked through the construction of a completeCore Data-based application, you’ll find performance tips and troubleshooting information.

If you’ve already been using Core Data for a while, and keep wondering why your appcrashes when you work with large numbers of model objects, or can’t figure out whyyou’re suffering a performance hit in certain situations, this book will help clear up anymysteries with the fundamentals of the framework, and help you use Apple’s developertools to isolate the sources of those problems.

Who Shouldn’t Read This Book

Core Data is definitely not the easiest to understand of the Cocoa Touch frameworks. Ifyou’ve never created an iOS application before, or struggle to remember the differencebetween a UIView and a UIViewController, you’ll have problems working through thisbook.

Although the first few chapters aim to flatten the learning curve as much as possible, it’sassumed that you have a solid understanding of both the Objective-C language, and theCocoa Touch framework. If you don’t, you’d be better looking at a suitable introductoryiOS programming book.

It’s also worth noting that Core Data is commonly mistaken for a database. Although CoreData can use SQLite, it’s not by any means a SQLite wrapper nor is it designed for typicaldatabase usage. If what you really need is a database, Core Data may not be the right solu-tion and this book might not be appropriate.

Finally, if you’re looking for creative visual interface inspiration, or suggestions for stun-ning data representations, you might prefer to look elsewhere. The sample applications inthis book are specifically designed with interfaces that are as simple as possible to helpyou learn the Core Data framework with minimal distractions. For this reason, all thesample projects are for iPhones or iPod touches, and don’t include iPad-specific resources.Equally, if you’re looking for tips to beautify table views or design jaw-dropping customviews, you’ll likely be disappointed.

Do bear in mind, however, that just because many of the sample projects in this bookmake use of the more traditional data display controls (i.e., table views), you can use CoreData in any situation where you need easy and efficient access to data. Need to store a listof high scores to draw in an OpenGL view for a game? Core Data makes that easy (well,the storage part anyway). Need to store enough information to draw icons that representthe weather for the next 24 hours? Core Data can help with that too.

xii Core Data for iOS

What You Need to Know

The book also assumes that you’re familiar and comfortable with Xcode and programmingin Objective-C. You won’t find any primers on how to define a method, or how to installand launch Xcode; there are plenty of entry-level books for newbies and converts fromother platforms and programming environments, and if you’re messing around with datamodels and such, we can assume that you’ve already got that grounding.

As with any iOS development, you’ll need at least a free Apple developer account. To testyour applications on real devices, or sell on the App Store, you’ll need a paid iOS devel-oper account ($99 per year at the time of writing). Go to developer.apple.com/devcenter/ios to register for access to all of the relevant updates for iOS, as well as Xcode,developer documentation, sample code, and even the session videos from Apple’s annualWorld Wide Developer Conference. Without a paid account it’s still possible to developiOS code, but you’ll only be able to run this code on the iPhone Simulator. While theSimulator is extremely useful, it’s no substitute for getting your code on a real iOS device.

Core Data can support a number of different persistent store types, the inner workings ofwhich it mostly hides from the developer. By far the most common type on iOS devices isthe SQLite store, which saves persistent data into a SQLite database. You don’t need toknow anything about SQLite to read this book, but if you’re already a database super-user,you’ll probably know that there is some controversy about the pronunciation of SQLite.D. Richard Hipp, the creator of SQLite, pronounces it “like a mineral”, pronouncing Ess-Queue-Ell-Ite as one might pronounce “pyrite” or “kryptonite”.1 Hipp does not insist onthis pronunciation though, and in practice the vast majority of Mac and iOS developerswe’ve encountered pronounce it Sequel-ite. For this reason we’ve chosen the latterpronunciation, so you’ll find we talk about “a SQLite store” rather than “an SQLite store.”

How This Book is Organized

The book offers a comprehensive discussion of Apple’s Core Data framework as it applieson iOS devices, building a firm grounding in the subject before covering more advancedand real-world examples of its use. Many of the chapters in the book are divided into twoparts—you start by learning the relevant information, and then cement your understand-ing by putting the knowledge into practice with a sample project.

Chapter 10 walks you through the complete construction of a Core Data-based notetaking application, from start to finish. If you want to jump straight in and find outwhat’s possible with Core Data, you might like to begin with Chapter 10 to whet yourappetite, then return to the beginning of the book to find out how it all works.

1 Hipp discussed “SQLite” pronunciation at the C4[2] conference in September 2008. His presentationcan be viewed at http://www.viddler.com/explore/rentzsch/videos/25/

xiiiPreface

. Part I: Introduction

Apple’s Core Data framework presents a unified and powerful solution to storing anapplication’s data. This book offers a comprehensive reference for the framework andits use in versions of iOS from iPhone SDK 3.0 onwards. As well as covering CoreData basics, this section discusses more general topics like object modeling and datapersistence, and demonstrates how to build an object model using Xcode’s datamodeling tool.

. Chapter 1: An Overview of Core Data on iOS Devices

This first chapter introduces Core Data as a framework to fit into the MVC-pattern for development of applications for iOS. It gives a brief outline of itshistory as the Enterprise Objects Framework for web development, beforediscussing when, how and why Core Data is useful. It explains how there islittle difference between working with Core Data on the desktop and on iOS,with the notable exception of the lack of support for Bindings on iOS. Theoverview finishes by showcasing a few real-world examples of Core Data use inpublicly-available iOS applications, including MoneyWell for iPhone,Calcuccino and the Associated Press news application.

. Chapter 2: A Core Data Primer

Having given a high-level overview in Chapter 1, this chapter delves deeperand introduces the key features in Core Data, covering the interaction betweenManaged Object Contexts, Managed Objects and the underlying PersistentStores. It also introduces the framework classes behind these and explains howimpressive functionality can be achieved with very little code, often withoutthe need to subclass the basic framework classes. The chapter continues byexplaining the process of writing applications that use Core Data. It concludesby taking a look at what is happening behind-the-scenes in Apple’s Xcodetemplate projects for Core Data iOS applications.

. Chapter 3: Modeling Your Data

This chapter introduces general ideas behind data modeling. Having expressedclearly that Core Data is not in itself a database, the chapter does discuss basicrelational database techniques and relevant best practices (for example, datanormalization that applies to object model design). This chapter also explainshow data stored in a relational database can be mapped into a relational objectmodel for use in object-oriented programming languages and concludes with ademonstration of how an object model is defined for Core Data using the DataModel editor in Xcode.

. Part II: Working with Core Data

The second part of the book focuses on a discussion of topics that apply to mostapplications wanting to make use of Core Data on iOS. Each facet of the frameworkor its related technologies is given a separate chapter so it is possible either to readthis part of the book in order, building knowledge in incremental steps, or to pick

xiv

out the chapters that are of particular interest. Each of these chapters is divided intotwo sections: the first introduces the particular feature or functionality, discusseswhy and when it might be useful, then walks through the relevant classes andmethods; the second section is written in a tutorial format that starts by adding abasic feature to a simple application, before building on more advanced functional-ity. The aim of these tutorial sections is to enable you to learn by doing, but in sucha way that you relate the same techniques to your own applications.

. Chapter 4: Basic Storing and Fetching

This chapter guides you through the process of building a simple iPhone appli-cation that uses a UITableView to display managed objects. It includes moreinformation about managed object contexts, and how they relate to the under-lying data—a good understanding of managed object contexts is absolutelyfundamental to using Core Data effectively. This chapter explains whatcontexts are, how to use them, where a context ‘comes from’ and how theyinteract with each other and the data store. The project for this chapterfeatures a simple Add button to add objects that are fetched and displayed in atable view; to keep it simple for now, each object is pre-populated withrandomly-generated information.

. Chapter 5: Using NSFetchedResultsController

This chapter demonstrates how to make use of the Fetched Results Controller,an object unique to iOS, to handle much of the functionality necessary tofetch and display objects in a table view. It explains why memory usage is soimportant on iOS, and how a fetched results controller works to keep to aminimum the number of objects held in memory at any one time.

. Chapter 6: Working with Managed Objects

This chapter introduces the functionality provided by NSManagedObject, suchas basic data validation. Although it frequently isn’t necessary to subclassNSManagedObject, this chapter explains why, when and how to do so. You’lllearn about the lifecycle of managed objects, and look at different types ofmodeled properties. The chapter covers features offered by Objective-C 2.0 tosimplify accessor method code and finishes by looking at custom validationlogic.

. Chapter 7: Working with Predicates

This chapter begins with the basics of creating an NSPredicate, discussingsimple predicate format strings. You’ll learn how to use predicates to matchagainst scalar values like numbers or dates, and also how to match objects,particularly across relationships, such as when fetching employees who workin a specific department. There’s a whole section dedicated to working withstrings, including information on case sensitivity, and you’ll see how toexamine the raw SQL that Core Data generates to query a SQLite store.

Core Data for iOS

xvPreface

. Chapter 8: Migration and Versioning

This chapter looks at how to use the provided versioning and migration func-tionality to maintain compatibility between old and new versions of an appli-cation’s data model. By default, an application built around a newer modelversion won’t be able to open an older version’s model; through using auto-matic migration, the user can continue to work with their old data even afteran application upgrade has occurred. You’ll learn about both simple migration,where the Core Data framework itself works out how one data model versionrelates to another, as well as custom migration using mapping models andentity migration policies.

. Chapter 9: Working with Multiple View Controllers and Undo

To keep the examples as simple as possible, and to minimize distractions, theprevious projects up to this point have made use of only a single viewcontroller. In this chapter, you’ll see how to keep track of managed objectcontexts across multiple view controllers, and how to use editing viewcontrollers to change values on existing managed objects. You’ll learn how towork with multiple managed object contexts, and find out how to refer tomanaged objects across these multiple contexts, before finding out how simpleit is to make use of the automatic Undo functionality provided by Core Data.

. Part III: Building a Simple Core Data Application

The third part of the book takes the reader through building a complete applicationusing Core Data.

. Chapter 10: Sample Application: Note Collector

This chapter puts your Core Data knowledge into context by walking throughthe creation of a more substantial application than you’ve worked with so far.You’ll see how to work with abstract entities, entity inheritance and multipleview controllers to create a fully functional note-taking application that storesnotes and organizes them in collections.

You’ll learn how to examine a raw SQLite file to peek at what Core Data isdoing, and find out how to include a pre-populated data store so that users ofthe application see some sample data when they launch the application for thefirst time. You’ll also look at one way to persist application state acrosslaunches, seeing how to archive the managed object information necessary torecreate a navigation-based stack of view controllers.

. Part IV: Optimizing and Troubleshooting

The final part of the book looks at performance issues, optimization for therestricted memory requirements of iOS devices, and at debugging tools to aid indeveloping with Core Data on iOS.

xvi

. Chapter 11: Optimizing for iOS Performance and Memory Requirements

This chapter is all about performance, optimization, and speed. You’ll learnsome simple tricks to help your application run faster and be more responsivefor the user without consuming all available memory or running down thebattery. This chapter assumes you already understand about retain counts andwhen objects are deallocated, which affects your memory usage but which arenot directly related to Core Data.

. Chapter 12: Troubleshooting Core Data

When things go amiss with Core Data the symptoms and error messages canseem obscure, even if you’ve been using it for a while. You can’t very well fixyour code if you don’t understand what’s wrong. In this chapter, you’ll look atways to help you diagnose and fix some of the most common Core Data prob-lems. Keep in mind that Core Data can be affected by problems that are notspecific to Core Data; for example, memory management errors can affect anyCocoa object, and managed objects are no exception. This chapter focuses onproblems specifically related to Core Data.

Although the book is designed to be read in order, each chapter is mostly self-contained,so feel free to skip around to learn about specific topics. Some of the example projects ineach chapter require code from a previous chapter as a starting point; if you need to graba ready-made project from an earlier chapter, the sample code for the book is availableonline.

About the Sample Code and Coding Style

All of the source code necessary to run the examples in this book is provided inline withinchapters; in order to fit within the confines of a page, the code may have rather morenewline characters than you might expect.

Because of the nature of the subject, the code includes a large number of accessormethods. As this book is likely to be read both by developers who prefer using full acces-sor methods and lots of nested square brackets, as well as those who have embracedObjective-C 2.0 dot syntax, we felt it important to include examples demonstrating bothstyles. The included code therefore uses a mixture of both traditional method calls anddot notation throughout the example listings. Feel free to substitute according to yourown coding preferences.

The complete source code for the projects in this book is available as a downloadable diskimage (.dmg), which you can get by clicking on the Resources tab on the book’s catalogpage:

http://www.informit.com/title/9780321670427

The disk image contains a README file along with folders containing the projects for eachchapter.

Apple shipped Xcode 4 (with substantial changes over Xcode 3) just before this book went

Core Data for iOS

xvii

to press. The screenshots in the book are taken from Xcode 4, but if you’re still usingXcode 3, it should be relatively straightforward to work out any differences. We’ve addedXcode 3-specific instructions in the text anywhere that there might be confusion overmajor differences.

Although Mac OS X Lion had been announced, it hadn’t yet shipped publicly when thisbook was published, so the screenshots are taken from Mac OS X Snow Leopard, which isthe current required environment for iOS (i.e., iPhone, iPad, and iPod touch) develop-ment. For Core Data development for iOS, you don’t need anything else: all the libraries,headers, and documentation are included with the Xcode tools and the iOS SDK.

Acknowledgments from Tim IstedAlthough writing a book notoriously takes longer than expected, I’ve certainly pushed theboundaries on this one. I have a vivid memory of the moment the words “Core Data”appeared on a slide at Apple’s announcement of iPhone SDK 3.0. Half an hour later,Chuck and I were discussing the outline for a book dedicated to Core Data on iPhone.That was back in June 2009.

Since then, the iPhone OS has become iOS, the iPad was released, iPhone 4 appeared,multitasking was introduced, Xcode 4 went public, and the goal posts kept moving. It’shard to pick a time to publish a book on something that changes so frequently, butputting overall iOS changes aside, the Core Data framework (and certainly its API) hasremained fairly stable, probably due to its earlier existence on the Mac. This book wouldnever have made it were it not for the wonderfully patient and encouraging editorial guid-ance Chuck Toporek has given me, not to mention his personal friendship. Together wehope we’ve ensured it should remain useful across the inevitable series of major iOSversion releases that will occur the moment the book hits the shelves.

After a few lengthy pauses for me to deal with various nasty bouts of illness among myclose family, Tom Harrington agreed to come on board to help get the book out before iOSbecame obsolete. His work specifically on the two performance chapters, together with hiscontributions across the whole book, has taken it up so many notches.

The four anonymous (for the most part) technical reviewers have been fantastic. It’s alltoo easy to become blinkered as an Indie developer and I thank the reviewers for savingme from too many of those “I’ve always done it like this” moments.

Finally, I can never thank enough the friends I have throughout the Mac/iOS developercommunity. It’s a wonderful team to be a part of.

Preface

xviii

Acknowledgments from Tom HarringtonI’d like to thank my wife Carey for encouraging me to embark on a career that appealed tome but seemed too risky to jump into. After the dot-com boom in 2001, Carey was theone who suggested there might be more interesting things to do than look for anotherday job. I never expected to run my own business and would not have done so withoutCarey’s help. I’ve been independent ever since and have never looked back.

I’d also like to thank Tim Isted and Chuck Toporek for giving me the opportunity to workon this book, and to Marcus Zarra for introducing me to Tim in the first place. Also, thisbook would not have been possible without the technical reviewers who help make Timand I look good.

About the Authors

Tim IstedTim Isted has been writing software for Macintosh computers since 1995. He also buildsweb applications using Rails, PHP, and .NET and has been known to develop for Windowsmachines too. Also a professional musician and singing teacher, he tries to divide his timefairly equally between conducting, accompanying, teaching, and writing software.Previous musings on Core Data for desktop development can be found on his blog atwww.timisted.net, and he is also co-organizer of NSConference, a new Mac developerconference taking place in both Europe and the USA.

Tom Harrington

Tom Harrington switched from writing software for embedded systems and Linux to MacOS X in 2002 when he started Atomic Bird, LLC. After six years of developing highlyregarded Mac software he moved to iPhone in 2008. He develops iOS software on acontract basis for a variety of clients. Tom also organizes iOS developer events inColorado. When not writing software he can often be found on his mountain bike. Hiswebsite is www.atomicbird.com.

Core Data for iOS

CHAPTER 2

A Core Data Primer

IN THIS CHAPTER

. Persisting Objects to Disk

. The Core Data Approach

. Examining the Xcode Core DataTemplates

In order to get the most out of Core Data, it’s extremelyimportant to have a firm understanding of its fundamentaloperations. Over the course of this chapter, you’ll learn thekey terms and features of the different parts of a Core Data-based application.

Before looking at the Core Data terms, though, take amoment to think about how you might work with persisteddata in an application without using Core Data.

Persisting Objects to DiskWhen you’re working with data to be saved in an applica-tion, you typically have collections of objects, maybe heldin arrays, sets or dictionaries, which need to be archived todisk. When it comes time to save the data, you mightencode or serialize those objects ready to be saved into abinary file or, for small datasets, store them in a .plist file.

As an alternative to working with binary files, and beforeCore Data came to iOS, developers could also make directuse of SQLite, a simple and very lightweight database, avail-able on iOS devices since the early versions of iPhone OS.When writing an application that made use of large collec-tions of objects, it would make sense to store those items ina database, offering huge increases in speed when savingand fetching objects.

SQLite, as its name implies, is based around the StructuredQuery Language, or SQL. You talk to an SQL database byissuing commands to, for example, insert or select (fetch)data. If you only need a specific object from the database,you can issue a command to fetch just that object; you

10 CHAPTER 2 A Core Data Primer

don’t need to worry about the efficiency and performance issues with loading an entirebinary file from disk just to get hold of a particular object.

In order to work with SQLite, however, you need to make heavy use of procedural C APIs,writing lengthy portions of code to handle data access. To save an object into a SQLitedatabase, for example, you would need to write out a string containing an SQL INSERTstatement, populate that string with the values held by the object’s instance variables,convert the string to a C-string, before finally passing it to a C function.

The Core Data ApproachCore Data, on the other hand, combines all the speed and efficiency of database storagewith the object-oriented goodness of object serialization.

Entities and Managed Objects

When you create your model objects, instead of starting out by writing the .h @interfacefor the class, you typically begin by modeling your entities, using the Xcode Data Modeler.An entity corresponds to one type of object, such as a Patient or Doctor object, and setsout the attributes for that entity, such as firstName and lastName. You use the datamodeler to set which attributes will be persisted to disk, along with various other featuressuch as the type of data that an attribute will hold, data validation requirements, orwhether an attribute is optional or required.

When you work with actual instances of model objects, such as a specific Patient object,you’re dealing with an instance of a managed object. These objects will either be instancesof the NSManagedObject class, or a custom subclass of NSManagedObject. If you don’tspecify a custom subclass in the modeler, you would typically access the attributes of theobject through Key Value Coding (KVC), using code like that in Listing 2.1.

LISTING 2.1 Accessing the attributes of a managed object

NSManagedObject *aPatientObject; // Assuming this has already been fetched

NSString *firstName = [aPatientObject valueForKey:@”firstName”];

NSString *lastName = [aPatientObject valueForKey:@”lastName”];

[aPatientObject setValue:@”Pain killers” forKey:@”currentMedication”];

[aPatientObject setValue:@”Headache” forKey:@”currentIllness”];

If you choose to do so, you can also provide your own subclass of NSManagedObject, toexpose accessor methods and/or properties for your managed object, so you could use thecode shown in Listing 2.2. You’ll look at this in more detail in Chapter 6, “Working withManaged Objects.”

11The Core Data Approach

LISTING 2.2 Using a custom subclass of NSManagedObject

Patient *aPatientObject; // Assuming this has already been fetched

NSString *firstName = [aPatientObject firstName];

NSString *lastName = aPatientObject.lastName;

[aPatientObject setCurrentMedication:@”Pain killers”];

aPatientObject.currentIllness = @”Headache”;

You could also still access the values of the object using valueForKey:, etc., if you wish.

Relationships

The Data Modeler is also the place where you define the relationships between your enti-ties. As an example, a Patient object would have a relationship to a Doctor, and theDoctor would have a relationship to the Patient, as shown in Figure 2.1.

2

When modeling relationships, you typically think in relational database terms, such asone-to-one, one-to-many, and many-to-many. In the example shown in Figure 2.1, a patienthas only one doctor, but a doctor has many patients, so the doctor-patient relationship isone-to-many.

If the doctor-patient relationship is one-to-many, the inverse relationship (patient-doctor)is obviously many-to-one. When you model these relationships in the Data Modeler, youneed to model them both, explicitly, and set one as the inverse of the other. By setting theinverse relationship explicitly, Core Data ensures the integrity of your data is automati-cally maintained; if you set a patient to have a particular doctor, the patient will also beadded to the doctor’s list of patients without you having to do it yourself.

FIGURE 2.1 A Patient-Doctor relationship

12

You specify a name for each relationship, so that they are exposed in a similar way to anentity’s attributes. Again, you can either work with KVC methods, or provide your ownaccessors and property declarations in a custom subclass, using code like that in Listing 2.3.

LISTING 2.3 Working with relationships

Patient *aPatientObject; // Assuming this has already been fetched

Doctor *aDoctorObject = [aPatientObject valueForKey:@”doctor”];

Patient *anotherPatientObject; // also already fetched

anotherPatientObject.doctor = aDoctorObject;

// The inverse relationship is automatically set too

NSLog(@”Doctor’s patients = %@”, [aDoctorObject patients]);

/* Outputs:

Doctor’s patients = (

aPatientObject,

anotherPatientObject,

etc...

)

*/

It’s important to note that Core Data doesn’t maintain any order in collections of objects,including to-many relationships. You’ll see later in the book how objects probably won’tbe returned to you in the order in which you input them. If order is important, you’llneed to keep track of it yourself, perhaps using an ascending numerical index property foreach object.

If you’re used to working with databases such as MySQL, PostgreSQL, or MS SQL Server(maybe with web-based applications in Ruby/Rails, PHP, ASP.NET, etc.), you’re probablyused to every record in the database having a unique id of some sort. When you work withCore Data, you don’t need to model any kind of unique identifier, nor do you have todeal with join tables between related records. Core Data handles this in the background;all you have to do is to define the relationships between objects, and the framework willdecide how best to generate the underlying mechanisms, behind the scenes.

Managed Object Contexts

So far, the code in this chapter has assumed that you’ve fetched an object “from some-where.” When you’re working with managed objects and Core Data, you’re workingwithin a certain context, known as the Managed Object Context. This context keeps track ofthe persistent storage of your data on disk (which on iOS is probably a SQLite store) andacts as a kind of container for the objects that you work with.

CHAPTER 2 A Core Data Primer

13The Core Data Approach

2

Conceptually, it’s a bit like working with a document object in a desktop application—thedocument represents the data stored on disk. It loads the data from disk when a documentis opened, perhaps allowing you to display the contents in a window on screen. It keepstrack of changes to the document, likely holding them in memory, and is then responsiblefor writing those changes to disk when it’s time to save the data.

The Managed Object Context (MOC) works in a similar way. It is responsible for fetchingthe data from the store when needed, keeping track of the changes made to objects inmemory, and then writing those changes back to disk when told to save. Unless youspecifically tell the MOC to save, any changes you make to any managed objects in thatcontext will be temporary, and won’t affect the underlying data on disk.

Unlike a normal document object, however, you are able to work with more than onemanaged object context at a time, even though they all relate to the same underlying data.You might, for example, load the same patient object into two different contexts, andmake changes to the patient in one of the contexts (as shown in Figure 2.2). The object inthe other context would be unaffected by these changes, unless you chose to save the firstcontext. At that point, a notification would be sent to inform you that another contexthad changed the data, and you could reload the second context if you wanted to.

Although it’s less common to work with multiple contexts on iOS than it is on thedesktop, you typically use a separate context if you’re working with objects in the back-ground, such as pulling information from an online source and saving it into your localapp’s data. If you choose to use the automatic Undo handling offered by managed objectcontexts, you might set up a second context to work with an individual object, handlingundo for any changes to individual attributes as separate actions. When it was time tosave that object back into your primary context, the act of saving all those changes wouldcount as one undo action in the primary context, allowing the user to undo all thechanges in one go if they wanted to. You’ll see examples of this in later chapters.

FIGURE 2.2 Managed Object Contexts and their Managed Objects

14 CHAPTER 2 A Core Data Primer

Fetching Objects

The managed object context is also the medium through which you fetch objects fromdisk, using NSFetchRequest objects. A fetch request has at minimum the name of anentity; if you wanted to fetch all the patient records from the persistent store, you wouldcreate a fetch request object, specify the Patient entity to be retrieved, and tell the MOCto execute that fetch request. The MOC returns the results back to you as an array. Again,it’s important to note that the order in that array probably won’t be the same as the orderin which you stored the objects, or the same as the next time you execute the fetchrequest, unless you request the results to be sorted in a particular order.

To fetch specific objects, or objects that match certain criteria, you can specify a fetch pred-icate; to sort the results in a certain order, you can provide an array of sort descriptors. Youmight choose to fetch all the patient records for a particular doctor, sorting them by lastname. Or, if you had previously stored a numerical index on each patient as they werestored, you could ask for the results to be sorted by that index so that they would bereturned to you in the same order each time.

Faulting and Uniquing

Core Data also works hard to optimize performance and keep memory usage to aminimum, using a technique called faulting.

Consider what could happen if you loaded a Patient record into memory; in order thatyou have access to that patient’s Doctor object, it might seem that you’d want to have theDoctor object loaded as well. And, since you might need to access the other patientsrelated to that doctor, you should probably load all those Patient objects too. With thisbehavior, what you thought was a single-object fetch could turn into a fetch of thousandsof objects—every related object would need to be fetched, possibly resulting in fetchingyour entire dataset.

To solve this problem, Core Data doesn’t fetch all the relationships on an object. It simplyreturns you the managed object that you asked for, with the relationships set to faults. Ifyou try and access one of those relationships, such as asking for the name of the patient’sdoctor, the “fault will fire” and Core Data will fetch the requested object for you. And, asbefore, the relationships on a newly fetched doctor object will also be set to faults, readyto fire when you need to access any of the related objects. All of this happens automati-cally, without you needing to worry about it.

A managed object context will also ensure that if an object has already been loaded, it willalways return the existing instance in any subsequent fetches. Consider the code inListing 2.4.

LISTING 2.4 Fetching unique objects

Patient *firstPatient; // From one fetch request

Doctor *firstPatientsDoctor = firstPatient.doctor;

15Examining the Xcode Core Data Templates

2

Patient *secondPatient; // From a second fetch request

Doctor *secondPatientsDoctor = secondPatient.doctor;

/* If the two patients share the same doctor, then the doctor instance

returned after each fault fires will be the same instance: */

if( firstPatientsDoctor == secondPatientsDoctor )

{

NSLog(@”Patients share a doctor!”);

}

This is known as uniquing—you will only ever be given one object instance in anymanaged object context for, say, a particular Patient.

Persistent Stores and Persistent Store Coordinators

The underlying data is held on disk in a persistent store. On an iOS device, this is usually aSQLite store. You can also choose to use a binary store or even your own custom atomicstore type, but these require the entire object graph to be loaded into memory, which canquickly become a problem on a device with limited resources.

You never need to communicate directly with a persistent store, or worry about how it isstoring data. Instead, you rely on the relationship between the managed object contextand a persistent store coordinator.

The persistent store coordinator acts as a mediator to the managed object contexts; it’salso possible to have a coordinator talk to multiple persistent stores on disk, meaning thatthe coordinator would expose the union of those stores to be accessed by the managedobject contexts.

You won’t typically need to worry too much about persistent stores and coordinatorsunless you want to work with multiple stores or define your own store type. In the nextsection, you’ll see the code from the Xcode template project that sets up the persistentstore for you. Once this is dealt with, you’ll spend most of your time concentrating on themanaged objects, held within managed object contexts.

Examining the Xcode Core Data TemplatesNow that you have a better idea of Core Data terminology, let’s take a look inside a standardCore Data template project for an iOS application to see how all of this works in practice.

16 CHAPTER 2 A Core Data Primer

The Navigation-Based Project Template

The Xcode project templates for the Navigation-based, Split View-based, Utility andWindow-based applications all offer the option to Use Core Data, as shown in Figure 2.3.

To follow the rest of this chapter, launch Xcode and choose File > New > New Project(Shift-„-N), then select the Navigation-based Application template. Call the projectTemplateProject, and tick the Use Core Data checkbox.

When the project window appears, you’ll see that there are some extra items compared toa standard project. First, the project links to the CoreData.framework. Second, there is anitem called TemplateProject.xcdatamodeld. This defines the structure of your data model,which you build visually using the Xcode Data Modeler. Click on the file to open it.

There are two ways to view a data model in Xcode 4—as a Table or a Graph, as shown inFigure 2.4.

NOTE

Xcode 3 has only one editor mode, which combines the Table and Graph into a singleview.

The Data Modeler

At the top-left of the editor, you’ll see a list of Entities. In the template file, there is a singleentity, called Event. If you select this entity for display using the Table editor style, you’llsee a list of the entity’s attributes, relationships and fetched properties.

FIGURE 2.3 The New Project Window

17Examining the Xcode Core Data Templates

2

FIGURE 2.4 The two Editor Styles in the Xcode 4 Data Modeler

The Event entity has a single attribute listed, called timeStamp. If you click this attribute toselect it, and look in Xcode 4’s Data Model Inspector (Option-„-3), you’ll see that its Typeis set to Date.

This inspector offers a number of other options relating to that attribute. For example, thisis where you can choose to validate the data that is stored, or mark an attribute as beingoptional; these options are covered in Chapter 3, “Modeling Your Data.”

Xcode 4’s Graph editor style offers a visual representation of the entities in your objectmodel. At present, there is only a single entity in the model, but if there were more thanone, you would see the relationships between the entities represented by lines and arrowsconnecting the two, as in Figure 2.5.

Setting up the Core Data Stack

When working with data held in a persistent store, you will need to have built up a stackof objects; at the bottom is the actual persistent store on disk, then comes a persistentstore controller to liaise between the store and the next level, the managed object context,as shown in Figure 2.6.

It’s also possible to have more than one persistent store under the one coordinator, as wellas multiple managed object contexts (as discussed earlier in the chapter).

18 CHAPTER 2 A Core Data Primer

FIGURE 2.5 Relationships between objects in the Object Graph

Managed ObjectNSManagedObject

Managed Object ContextNSManagedObjectContext

Managed ObjectNSManagedObject

Managed ObjectNSManagedObject

Managed ObjectNSManagedObject

Persistent Store CoordinatorNSPersistentStoreCoordinator

(uses a managed object model)

Persistent StoreNSPersistentStore

Persistent StoreNSPersistentStore

Managed Object ContextNSManagedObjectContext

FIGURE 2.6 The Core Data Stack

Let’s examine the template code provided to set up this Core Data stack. Open theTemplateProjectAppDelegate.h interface file, and you’ll find that there are a number ofproperty declarations defined for the app delegate, as shown in Listing 2.5 (the Xcode 4templates make use of the modern runtime feature of synthesizing the correspondinginstance variables).

19Examining the Xcode Core Data Templates

2

LISTING 2.5 The app delegate interface

@interface TemplateProjectAppDelegate : NSObject <UIApplicationDelegate> {

}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain, readonly) NSManagedObjectContext

*managedObjectContext;

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;

@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator

*persistentStoreCoordinator;

- (void)saveContext;

- (NSURL *)applicationDocumentsDirectory;

@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@end

The app delegate keeps track of the managed object model, which is the informationcontained within the TemplateProject.xcdatamodeld file. It also has a reference to apersistent store coordinator, along with a managed object context. TheapplicationDocumentsDirectory is used to determine where the data will be held on disk.

Switch to the TemplateProjectAppDelegate.m interface file and scroll through the variousmethods that are provided. Near the bottom, you’ll find theapplicationDocumentsDirectory method. As the name implies, it simply returns the pathto the application’s documents directory.

Next find the persistentStoreCoordinator method. This method sets up a persistentstore coordinator, to access a SQLite store file called TemplateProject.sqlite, located inthe application’s documents directory. The persistent store is initialized using the modelprovided by the managedObjectModel method, so jump to this method next.

The managedObjectModel method returns an NSManagedObjectModel object created from afile called TemplateProject.momd. When you compile the project, theTemplateProject.xcdatamodeld data model is compiled into this .momd resource andstored in the application’s bundle.

It’s also possible to create an NSManagedObjectModel by merging all the available modelfiles using the class method mergedModelFromBundles:, or by merging selected modelsusing modelByMergingModels:. Although there is only a single model file (it’s actually amodel bundle) in this template application, it is possible to split your model into multiple.xcdatamodeld files, if you wish.

20 CHAPTER 2 A Core Data Primer

At the top of the stack, you’ll find the managedObjectContext method. This method sets upthe context using the persistent store coordinator. If you look in the awakeFromNib method,towards the top of the file, you’ll find that it sets a property on the RootViewController fora managedObjectContext. It is at this point that the chain is triggered to set up themanaged object model, persistent store coordinator and finally the context.

NOTE

In earlier versions of Xcode, the template code may be slightly different; for example,setting up the managed object model by merging the models in the main bundle, andsetting the RootViewController’s managedObjectContext property from withinapplication:didFinishLaunching:.

Lastly, the applicationWillTerminate: method calls a saveContext method, which checksto see whether any changes have been made to objects in the managed object context,and tries to save those changes if so. This means that the persistent store will be updatedwith changes from the context when the application exits. Some versions of the projecttemplate also call saveContext from applicationDidEnterBackground:, so that the storewill be updated if the user switches to a different application under iOS 4 multitasking.

You probably won’t need to modify the code in these methods unless you need to workwith multiple stores or custom store types. Once the managed object context has been setup, it’s passed to the root view controller. This view controller has the code that actuallyperforms the relevant fetches to display the data in a table view, and it’s this sort of codethat you will typically be writing most of the time when you’re working with Core Data.In Chapter 4, “Basic Storing and Fetching,” you’ll start writing your own code to populatea table view with information from a Core Data store.

Running the Application

To see the functionality you get from the basic project template, build and run the appli-cation. You’ll find that you can add to a list of Events; the table view shows these,outputting the values of the events’ timeStamp attributes. Note that you can remove itemsfrom the table view using the Edit button, or by swiping your finger across a row.

A Quick Look at the RootViewController Code

To get an idea of how this all works, open up the RootViewController.m implementationfile. The template application makes use of a Fetched Results Controller to simplify workingwith fetched objects and table views. This object is created lazily and told to fetch whenit’s needed by one of the table view data source methods.

NOTE

In earlier versions of Xcode, the template file creates the FetchedResultsControllerand executes a fetch at the end of the view controller’s viewDidLoad method.

21Examining the Xcode Core Data Templates

2

If you look at the code that generates the fetchedResultsController lazily, you’ll see thatit’s set to use the Event entity and given sort descriptors to sort by the timeStamp attribute.

The methods to display the contents in the table view are the standard table view datasource methods; for the numberOfSections... and numberOfRows... methods, thetemplate code just queries the fetched results controller object. To display the informationin the cellForRowAtIndexPath: method, a configureCell:atIndexPath: method is used.Notice how simple it is to get hold of the managed object at the selected index. The codeto display the time stamp is shown in Listing 2.6.

LISTING 2.6 Displaying the timestamp in the cell

NSManagedObject *managedObject = [self.fetchedResultsController

objectAtIndexPath:indexPath];

cell.textLabel.text = [[managedObject valueForKey:@”timeStamp”] description];

The fetched results controller returns the object at the specified index, and the code justqueries that returned object for the description of its timeStamp key.

The commitEditingStyle:forRowAtIndexPath: method simply tells the managed objectcontext to delete the object at the specified index path, and then asks the context to save.

FIGURE 2.7 The Template Application in the Simulator

22 CHAPTER 2 A Core Data Primer

This will mean that the object deleted from the table view will also be deleted from thepersistent store.

Lastly, find the insertNewObject method that gets called when the user tries to add anobject to the table view, and you’ll see that the procedure is:

. Get a pointer to a managed object context.

. Decide which entity you need to use to create a new object.

. Insert a new object for that entity, into the managed object context.

. Set the relevant values on the new object.

. Tell the context to save.

When the context saves, the new object is written to the persistent store. It’s as simple asthat! Note that the template files are deliberately verbose—it’s common to accomplish theabove using only two or three lines of code.

SummaryNow that you have an idea of how a Core Data application is constructed, it’s time to startlearning how to use the individual parts of the Core Data framework. In the next chapter,you’ll see best practices for constructing managed object models from the point of view ofmemory and performance considerations.

Although the Apple-provided template application makes use of a fetched resultscontroller, it’s a good idea to see how objects are fetched manually. Chapter 4, “BasicStoring and Fetching,” demonstrates how to work directly with managed object contextsand fetch requests to display objects in a table view. Chapter 5, “UsingNSFetchedResultsController,” then shows how to take advantage of the memory optimiza-tion and performance benefits offered by the fetch results controller.

SYMBOLS” (quotation marks), substituting without

strings, 119#ifdef directive, 218= (equality) operators, 124@dynamic keyword, 58, 91@end keyword, 107

AAbstract checkbox, 31abstract entity models, 189AbstractItem entity, 232abstract sub-entity models, 189-190accessing

managed objects, 10relational database systems, 3

accessor methodscustomizing, 91-93lazy, 109non-transient properties, 109troubleshooting, 266-267

actions, deleting undo, 181Add Attribute button, 31add button (+), 227Add button, viewing, 50Add (+) button (Xcode), 31Add Entity button, 29adding

attributes, 148, 242AWPerson interfaces, 106-108convenience methods, 94delegate methods, 77editor controllers, 182-183entities, 148frameworks, 256ImageFilename property, 242objects, 96outlets to view controllers, 164persistent stores, 146PrimitiveAccessors categories, 110properties, 166, 196RandomDate objects, 50relationships to entities, 35-37Search Bars, 139-141Search Display Controllers, 130-141SQLDebug arguments, 227

Index

support to managed object contexts, 176transient eyeColor property declarations,

108addNewPerson method, 183addNewRandomDate method, 50, 58, 75allocating

memory. See memoryobjects, 114

AND operator, 128APIs (application programming interfaces), 10application:didFinishLaunchingWithOptions:

method, 174application programming interfaces. See APIs

(application programming interfaces)applications, 3

Associated Press, 7Calcuccino, 7contact-management, 27data models, 188-192delegates, 254iPhone screens, 26MoneyWell case study, 6-7Note Collector, 187-188

AbstractItem entity, 232BLOBs (Binary Large OBjects), 239configuring RootViewController, 192-195data models, 188-192editing notes, 210-217naming items, 202-210SQLite debug level 1, 228supplying pre-populated data stores,

217-219viewing collection contents, 195-202

Random Dates, 47-48NSFetchedResultsController, 73-85section index titles, 82table views, 80

Random Peopleadding Search Display Controllers,

130-141configuring, 93-98creating, 88-89customizing migration, 151editing managed objects, 163-173managed object subclass files, 88troubleshooting, 105undo support, 174-175

running, 20Template, 21testing, 135

applicationWillTerminate: method, 20applying

Boolean attributes, 90Data Modelers (Xcode), 10, 28-37managed objects, 87NSFetchedResultsController, 61predicates, 117relationships, 12sort descriptors, 45table views, 46-54transformable attributes, 113-114transient attributes, 105-113UIColor properties, 111-113

archives, 9arguments, 226

SQLDebug, configuring, 228validation methods, 100XCode, 228

Arguments Passed On Launch section, 227arrays, 9, 128arrows, relationships, 36assigning attributes, 42Associated Press application, 7atomic binary data stores, 224attaching instruments, 246Attribute Inspector, 204attributes

adding, 148, 242assigning, 42Boolean, applying, 90configuring, 42custom managed object subclasses, 55data, 27Data Modelers (Xcode), 32Decimal, 34eyeColorData, 107fullName, 107Integer16, 34managed objects, accessing, 10naming, 33optional, 32orderDate, 33persistent, 92renaming, 148-152String, 35testAttribute, 144transformable, 34, 113-114Transient, 32transient, applying, 105-113types, 34yearOfBirth, 156

Attributes Inspector, 212auto-generated AWPerson class interface, 89automaticallyNotifiesObserversForKey: method,

91automatic grouping functionality, 68automatic undo support, 174AWAbstractItem entity, 195AWAbstractItem.h file, 191awakeFromFetch method, 115awakeFromInsert method, 115awakeFromSnapshotEvents: method, 115AWCollectionViewController, 196AWNoteEditorViewController, 211AWNoteEditorViewController.h file, 211AWNote.h file, 191AWPersonEditorViewController, 176, 182AWPerson interfaces, adding, 106-108AWStringEditorVCDelegate protocol, 203AWStringEditorViewController class, 203AWStringEditorViewController.h file, 203

Bbackground colors, 112batches

faulting, 237fetching, 62rows, loading, 62

behaviormigration, customizing, 156overriding, 80RootViewController class, 49-51

binary data storage, 27-28, 225binary files, 9Binary Large OBjects. See BLOBsBindings, 5bitwise operators, predicates, 123blank documents, 29BLOBs (Binary Large OBjects)

entities, 239-242external files, 242-244management, 238-244migration, 244

Boolean attributes, applying, 90bundles, xcdatamodeld, 146

Ccaching, 63

NSFetchedResultsController, 72objects, 234specifying, 84

Calcuccino, 7canBecomeFirstResponder method, 174Cancel button, 205canceling edited strings, 207

applications272

cancelPerson: method, 171cascading objects, 46case studies

Associated Press application, 7Calcuccino, 7MoneyWell for iPhone, 6-7

categories, adding PrimitiveAccessors, 110cellForRowAtIndexPath: method, 21

modifying, 59cells

backgrounds, formatting colors, 112contents, viewing, 193index paths, returning, 66timestamps, viewing, 21

C language, APIs (application programminginterfaces), 10

classesAWStringEditorViewController, 203customizing, 56-59factory methods, 55files, creating, 190-192managed objects

implementation, 90-93interfaces, 89-90

not found errors, 255-256NSCompoundPredicate, 128NSEntityDescription, 42NSFetchedResultsController, 6NSManagedObject, 11NSObject, 23NSPredicate, 118, 126, 231RandomDate, 58RootViewController, 49-51specifying, 30subclasses, customizing, 11

clearing fetch predicates, 135-136code, RootViewController, 21-22collections, 9

contents, viewing, 195-202items, placing inside, 199tracking, 196view controllers, initializing, 198

collisions, threading, 260-264colors, 111

backgrounds, 112commands

Copy (Xcode), 106Paste (Xcode), 106

commitEditingStyle:forRowAtIndexPath:method, 22

comparing strings, 124-126comparison operators, predicates, 122-123

How can we make this index more useful? Email us at [email protected]

compound predicates, 126-129conditions, specifying predicates, 126configureCell:atIndexPath: method, 21, 97configuring

attributes, 42controls, 213currentPerson property, 165custom classes for managed objects, 56-59Delete Rule, 36fetching

limits, 230-231predicates, 132-135

Fetch Predicates, 44items, naming, 202-210managed object values, 168Random People application, 93-98RootViewController, 192-195SQLDebug arguments, 228stacks, 17-20strings, first responders, 206undo managers, 180

conflicts, handling, 260-264connections, Search Display Controllers, 132consoles, Xcode, 252contact-management applications, 27contents

cells, viewing, 193collections, viewing, 195-202

contextsediting, 180managed objects

editing, 177resetting, 181-182

MOC (Managed Object Context), 12-13multiple managed object, 175-183objects, modifying, 69-72saving, 42-43

contextual menus for attributes (Xcode), 106controllers

editors, adding objects, 182-183fetched results, 6, 68, 192main view, loading, 254NSFetchedResultsController, 62. See also

NSFetchedResultsControllerRootViewController code, 21-22Search Display Controllers, adding, 130-141views

adding outlets to, 164creating, 203-210generating, 166initializing, 176, 198multiple, 163viewing, 167

controllers 273

controls, configuring, 213convenience methods, adding, 94convention, adding, 152converting objects, 237-238coordinators, persistent stores, 15Copy command (Xcode), 106copying pre-populated data stores, 218Core Data, when not to use, 248crashes, 43, 252, 265-266. See also

troubleshootingcreating. See formattingcurrentPerson property, 165customizing

accessor methods, 91-93classes, 56-59entities, 156-160migration, 151order of section of index titles, 82sections, returning index titles, 81subclasses, 11

custom managed object subclassesattributes, 55interfaces, 55

Ddatabases, 10

normalization, 25relational database systems, 3SQL (Structured Query Language), 4storage, 10

data conflicts, handling, 260-264Data Modeler (Xcode), 10, 16-18

applying, 28-37describing entities, 23-24fetch requests, editing, 121relationships, 11-12

Data Model Inspector (Xcode), 30, 149data models, applications, 188-192data normalization, 25-26data source methods, 64-72data stores, types, 224-230data validation. See validationdateFilterPredicate method, 140datePickerValueDidChange: method, 180dates

filters, 140validation, 100

debugging, 226. See also troubleshootingDecimal attribute, 34declaring relationships, 107decreased property, 92Default text field, 33

definingentities, 35relationships, 4store types, 15

delegatesapplications, 254methods

adding, 77writing, 95

deleteCacheWithName: method, 72deleteObject: method, 45Delete Rule, 36deleting

managed objects, 45-46objects, 76RandomDate objects, 53undo actions, 181validation prior to, 104

denying objects, 46design, data models, 24-28desktops, differences between Core Data iOS

and, 5-6Destination drop-down box, 36detail disclosure indicators, 167Detection options, 212devices, overview of, 3dictionaries

sets of, 9troubleshooting, 129

DidChangeContent method, 69didChangeObject method, 78directives, #ifdef, 218directories, Documents, 149disks, persisting objects to, 9-10displaying. See viewingdividing data into entities, 24-28documents, blank, 29Documents directory, 149Done button, 205

EEdit button, 54editing

contexts, 180enabling, 215fetch requests, 121items, naming, 202-210managed objects, 163-173, 177notes, 210-217preventing, 136strings, saving, 207

controls, configuring274

editingContext property, 176editors

controllers, adding objects, 182-183Graph, 17, 31, 106mapping models, 154notes, interfaces, 211Table, 31

Edit Scheme window, 226efficiency of databases, 10enabling

debugging, 226editing, 215lightweight migration, 146-148

Enterprise Objects Framework. See EOFEntities, 16entities

abstract, models, 189AbstractItem, 232adding, 148AWAbstractItem, 195BLOBs (Binary Large OBjects), 239-242creating, 29-31, 34customizing, 156-160dividing data into, 24-28Event, 145managed objects and, 10-11, 23-24modifying, 149renaming, 148-152

Entity Inspector, 31, 56Entity list, 29Entity Mappings list, 156environment variables, 226EOF (Enterprise Objects Framework), 3equality (=) operators, 124errors, 43

executeFetchRequest:error:, 45migration, 143-145troubleshooting, 251-256. See also

troubleshootingvalidation, 103

evaluating statements, 117. See alsopredicates

Event entities, 145Executables section, 228executeFetchRequest:error:, 45executing fetch requests, 44, 63, 122expressions, NSPredicate class, 126Extensible Markup Language. See XMLexternal files, BLOBs (Binary Large OBjects),

242-244eyeColorData attribute, 107

How can we make this index more useful? Email us at [email protected]

Ffactory method classes, 55faulting, 14-15

batches, 237management, 235-238objects, re-faulting, 237-238troubleshooting, 268-269

fetchedResultsController lazy accessor, 134fetched results controllers, 6fetching, 41

batches, 62data, 10limits, configuring, 230-231managed objects, saving, 44-45NSFetchedResultsController, 61objects, 14

persistent stores, 118troubleshooting, 269-270

optimizing, 230-235predicates

clearing, 135-136configuring, 132-135

properties, 31, 113RandomDate objects, 51-52requests

editing, 121executing, 44, 63, 122formatting, 44monitoring, 247predicates, 117. See also predicatesstoring, 120

results, 75, 192sorting, 113

fetchLimit property, 230Fetch Predicates, configuring, 44fetchRandomDates method, 73fields, text, 214files

AWAbstractItem.h, 191AWNoteEditorViewController.h, 211AWNote.h, 191AWStringEditorViewController.h, 203binary, 9BLOBs (Binary Large OBjects), 242-244classes, creating, 190-192LightweightMigrationTestAppDelegate.m,

146Managed Object Class, 57managed objects, subclasses, 87-93MigrationTest.xcdatamodeld, 144

files 275

raw data, viewing, 200-202RootViewController.h, 166support, searching, 149

filtersdates, 140Search Bars, adding, 139-141

first respondersstrings, 206view controllers, 174

for loops, compound predicates, 128Format Specifiers section, 118format strings, creating predicates, 118-120formatting

custom classes for managed objects, 56-59entities, 29-31, 34items, 194managed objects, 41-43NSFetchedResultsController, 62-64objects, 10, 43predicates, 118-120properties, 31-35Random People application, 88-89relationships, 35-37stacks, 17-20subclasses, 54-59view controllers, 203-210

frameworks, 3adding, 256EOF (Enterprise Objects Framework), 3

freeing up memory, 224fullName attribute, 107fullName property, 93functionality, 4, 25

automatic grouping, 68of Core Data, 4Note Collector application, 210. See also

Note Collector applicationundo, 163validation, 98

Ggenerating view controllers, 166getter methods

implementation, 92transient properties, adding, 108

Graph editor, 17, 31, 106

Hhandling

data conflicts, 260-264tap on accessory buttons, 206

Handling Underlying Data Changes section, 63headers

files, importing model class files, 192sections, 68

hiding keyboards, 166history of Core Data, 3-4

Iidentifiers, renaming, 150IDs, managed objects, 264ImageFilename property, adding, 242implementation

accessor methods, customizing, 91-93AWPerson interfaces, adding, 106-108classes, managed objects, 90-93data source methods, 75getter methods, 92setter methods, 91

importing model class files, 192Indexed checkbox, 32indexes

paths, returning cells, 66titles, 68, 79, 81

infinite loops, 101inheritance, NSEntityMigrationPolicy, 156initializing

managed objects, troubleshooting, 265-266non-persistent properties, 114-116stacks, 253view controllers, 176, 198

init method, 178in-memory data stores, 224IN operator, 129insertNewObject method, 22, 193instances, variables, 73instantiation, fetched results controller sub-

classes, 81instruments, monitoring with, 245-248Integer16 attribute, 34Interface Builder, 5, 213Interface Editor, 5interfaces

APIs (application programming interfaces),10. See also APIs

AWPerson, adding, 106-108classes, managed objects, 89-90custom managed object subclasses, 55note editors, 211updating, 165

Inverse drop-down box, 36inverse relationships, 4, 11, 36

files276

iOSoptimizing, 223use of Core Data on, 4-5

iPhonesapplication screens, 26MoneyWell case study, 6-7OS 3.0, table views, 67

itemName property, 193items

collections, placing inside, 199creating, 194naming, 202-210

Jjoin tables, 24

Kkeyboards, hiding, 166key paths, predicates, 123-124Key-Value-Coding. See KVCKey-Value-Observing. See KVOkeywords

as attribute names, 33@dynamic, 58, 91@end, 107

KVC (Key-Value-Coding), 5, 10, 42, 54, 91KVO (Key-Value-Observing), 5

notifications, 91

Llazy accessor methods, 109lifecycles, managed objects, 114-116lightweight migration, 145-148LightweightMigrationTestAppDelegate.m file,

146LIMIT parameter, 230limits, configuring fetching, 230-231lists

Entity, 29Entity Mappings, 156

loadingmain view controllers, 254properties, preventing, 237rows, 62

loopsfor, compound predicates, 128infinite, 101

MMac OS X 10.4 Tiger, 3main view controllers, loading, 254

How can we make this index more useful? Email us at [email protected]

Managed Object Class file, 57Managed Object Context. See MOC (Managed

Object Context)managedObjectContext method, 20managedObjectContext property, passing, 49managedObjectModel method, 19managed objects

accessing, 10applying, 87attributes, configuring, 42binary data storage, 27-28classes

creating files, 190-192implementation, 90-93interfaces, 89-90

conflicts, 263contexts

editing, 177resetting, 181-182

creating, 41-43and data validation, 5deleting, 45-46editing, 163-173and entities, 23-24entities and, 10-11IDs, 264invalidation, 267-268lifecycles, 114-116MOC (Managed Object Context), 12-13multiple contexts, 175-183multithreading, 257predicates, 117. See also predicatesproperties, updating, 168-170saving, fetching, 44-45subclasses, 54-59, 87-93tracking, 164-168transformable attributes, 113-114transient attributes, 105-113troubleshooting, 265-269validation, 99-105, 171-173values

configuring, 168modifying, 179

managementBLOBs (Binary Large OBjects), 238-244contact-management applications, 27faulting, 235-238memory, 248-249relationships, 4state, 5

managers, configuring undo, 180

managers, configuring undo 277

many-to-many relationships, 4, 24mapping

models, 151-155modifying, 157object-relational, 3PersonToPerson, 156

memoryBLOBs (Binary Large OBjects), 238data stores, 225freeing up, 224management, 248-249performance, 27requirements, 223

merging changes from one context to another,176-178

messagescrashes, 265errors, 103, 252willSave, 110

methodsaccessor

customizing, 91-93lazy, 109non-transient properties, 109troubleshooting, 266-267

addNewPerson, 183addNewRandomDate, 50, 58, 75application:didFinishLaunchingWithOptions:,

174applicationWillTerminate:, 20automaticallyNotifiesObserversForKey:, 91awakeFromFetch, 115awakeFromInsert, 115awakeFromSnapshotEvents:, 115canBecomeFirstResponder, 174cancelPerson:, 171cellForRowAtIndexPath:, 21, 59commitEditingStyle:forRowAtIndexPath:, 22ConfigureCell:atIndexPath:, 21configureCell:atIndexPath:, 97convenience, adding, 94dateFilterPredicate, 140datePickerValueDidChange:, 180delegates

adding, 77writing, 95

deleteCacheWithName:, 72deleteObject:, 45DidChangeContent, 69didChangeObject, 78fetchRandomDates, 73getter, adding for transient properties, 108

init, 178insertNewObject, 22, 193managedObjectContext, 20managedObjectModel, 19NSFetchedResultsControllerDelegate, 69persistentStoreCoordinator, 19predicateForSearchString:, 139, 140primitiveValueForKey:, 92refreshObject:mergeChanges:, 237RootViewController.m, 159safe fault-free, 236-237save:, 46saveContext, 20savePerson:, 171sectionIndexTitleForSectionName:, 81-82setCurrentPerson:, 177, 182setRelationshipKeyPathsForPrefetching:,

234setter, adding for transient properties,

110-111tableView:didSelectRowAtIndexPath:, 199textFieldShouldEndEditing, 100textFieldShouldReturn:, 205userDidSaveStringEditorVC:... callback, 209validateValue:ForKey:error:, 102viewDidLoad, 50, 74, 96, 168viewWillDisappear:, 168, 181WillChange, 69

migration, 143BLOBs (Binary Large OBjects), 244lightweight, 145-148models, mapping, 151-155overview of, 143-145policies, custom entities, 156-160summaries, 155

MigrationTest.xcdatamodeld file, 144MOC (Managed Object Context), 12-13models, 3

abstract entities, 189abstract sub-entities, 189-190applications, 188-192entities, dividing data into, 24-28mapping, 151-155modifying, 106, 144-145naming, 152objects, 10, 41Random Dates data, 48Random People application, 89relationships, 11terminology, 24-25

modifyingaddNewRandomDate method, 58

many-to-many relationships278

cellForRowAtIndexPath: method, 59entities, 149lightweight migration, 148managed object values, 179mapping, 157models, 106, 144-145objects, 69-72persistent properties, 111predicates, searching, 136-139sections, 70

MoneyWell for iPhone case study, 6-7monitoring

with instruments, 245-248SQLite data stores, 225-227

multiple data model versions, 145-148multiple managed object contexts, 175-183multiple search words, creating predicates for,

137multiple view controllers, 163multitasking, 43multithreading, 257-258

Nnaming. See also renaming

attributes, 33entities, modifying, 149items, 202-210models, 152relationships, 36RootViewController, 195

Navigation-based project templates (Xcode),16-17

New File sheet, 28New Project window, 16NeXT, 3No Action Delete Rule, 46non-persistent properties, initializing, 114-116normalization, 25-26Note Collector application, 187-188

AbstractItem entity, 232BLOBs (Binary Large OBjects), 239collection contents, viewing, 195-202data models, 188-192items, naming, 202-210notes, editing, 210-217pre-populated data stores, supplying,

217-219RootViewController, configuring, 192-195SQLite debug level 1, 228

How can we make this index more useful? Email us at [email protected]

notesediting, 210-217editors, interfaces, 211

not found errors, classes, 255-256notifications

KVO (Key-Value-Observing), 91registering, 180

NSCompoundPredicate class, 128NSEntityDescription class, 42NSEntityMigrationPolicy

inheritance, 156objects, 156

NSError objects, 45NSFetchedResultsChangeDelete, 71NSFetchedResultsChangeInsert, 71NSFetchedResultsChangeMove, 71NSFetchedResultsChangeUpdate, 71NSFetchedResultsController class, 6

applying, 61caching, 72creating, 62-64data source methods, 64-72instances, variables, 73overview of, 62Random Dates application, 73-85sections, 235subclasses, 80-85

NSFetchedResultsControllerDelegate methods,69

NSInferMappingModelAutomaticallyOption, 147NSManagedObject class, 11NSManagedObject subclass, 56, 191NSMergeByPropertyObjectTrumpMergePolicy,

262NSMergeByPropertyStoreTrumpMergePolicy,

262NSMigratePersistentStoresAutomaticallyOption,

147NSObject class, 23NSOverwriteMergePolicy, 262NSPredicate class, 118, 126, 231NSRollbackMergePolicy, 263nullifying objects, 46

Oobject-relational mapping, 3objects

adding, 96allocating, 114BLOB (Binary Large OBject) management,

238-244caching, 234

objects 279

cascading, 46contexts, modifying, 69-72converting, 237-238creating, 43deleting, 76denying, 46disk, persisting to, 9-10editor controllers, 182-183EOF (Enterprise Objects Framework), 3fetching, 14managed. See managed objectsmodels, 10, 41modifying, 71NSEntityMigrationPolicy, 156nullifying, 46object-relational mapping, 3persistent stores, fetching, 118pre-fetching, 234-235RandomDate

adding, 50deleting, 53fetching, 51-52viewing, 52-53

re-faulting, 237-238relationship management, 4releasing, 114serialization, 10SQLite data stores, 225troubleshooting, 269-270unique, fetching, 14

one-to-many relationships, 4one-to-one relationships, 4operators

AND, 128IN, 129equality (=), 124OR, 128predicates

bitwise, 123comparison, 122-123

optimizingfetching, 230-235iOS, 223performance, 224predicates, 231-233

optional attributes, 32options

Detection, 212NSInferMappingModelAutomaticallyOption,

147NSMigratePersistentStoresAutomatically-

Option, 147

orderDate attribute, 33order of section of index titles, customizing, 82OR operator, 128overriding behavior, 80

Pparameters, LIMIT, 230Parent Entity, 30parsers, tokens, 118passing managedObjectContext properties, 49Paste command (Xcode), 106paths

indexes, returning cells, 66key, predicates, 123-124

performancememory, 27monitoring, 245-248optimizing, 224requirements, 223

persistent attributes, 92persistentStoreCoordinator method, 19persistent stores, 15, 43, 105. See also storage

adding, 146coordinators, 257objects, fetching, 118

persisting objects to disk, 9-10PersonToPerson mapping, 156policies, migration, 156-160predicateForSearchString: method, 139-140predicates

applying, 117bitwise operators, 123comparison operators, 122-123compound, 126-129conditions, specifying, 126creating, 118-120fetching

clearing, 135-136configuring, 132-135

key paths, 123-124optimizing, 231-233overview of, 117-124relationships, 129-130searching, modifying, 136-139sets, 129-130SQL queries, 130strings, comparing, 124-126variables, 120-122

pre-fetching. See also fetchingobjects, 234-235relationships, 233-234

objects280

pre-loading property values, 235pre-populated data stores, supplying, 217-219preventing

editing, 136property loading, 237

PrimitiveAccessors categories, adding, 110primitiveValueForKey: method, 92programming RootViewController code, 21-22project templates, 252properties

adding, 166collections, tracking, 196creating, 31-35decreased, 92editingContext, 176fetching, 31, 113fetchLimit, 230fullName, 93ImageFilename, adding, 242itemName, 193loading, preventing, 237managed objects, updating, 168-170non-persistent, initializing, 114-116sorting, 113specifying, 114synthesizing, 197, 204testing, 129transient, 105UIColor, applying, 111-113undoManager, 174validation, 99-104values

pre-loading, 235troubleshooting, 265-266

protocols, AWStringEditorVCDelegate, 203

Qqueries

fetched results, 68SQL predicates, 130

quotation marks (“), substituting withoutstrings, 119

RRandomDate class, 58RandomDate objects

adding, 50deleting, 53fetching, 51-52viewing, 52-53

How can we make this index more useful? Email us at [email protected]

Random Dates application, 47-48NSFetchedResultsController, 73-85section index titles, 82table views, 80

Random People applicationconfiguring, 93-98creating, 88-89managed objects

editing, 163-173subclass files, 88

migration, customizing, 151Search Display Controllers, adding, 130-141troubleshooting, 105undo support, 174-175

raw data files, viewing, 200-202redo, registering notifications, 180reducing memory usage, 224re-faulting objects, 237-238referential integrity, 4Refractor tool (Xcode), 195refreshObject:mergeChanges: method, 237registering undo/redo notifications, 180relational database systems, 3Relationship inspector, 35relationships, 25

applying, 12arrows, 36creating, 35-37Data Modelers (Xcode), 11-12declaring, 107management, 4naming, 36predicates, 129-130pre-fetching, 233-234superCollection, 192

releasing objects, 114remove button (-), 228renaming

attributes, 148-152entities, 148-152identifiers, 150RootViewController, 195

requestsfetching

editing, 121executing, 44, 63, 122formatting, 44monitoring, 247

NSFetchedResultsController, 61requirements

memory, 223performance, 223validation, 10

requirements 281

resetting contexts, managed objects, 181-182results

fetched results controllers, 6fetching, 75, 192NSFetchedResultsController, 61troubleshooting, 270

returningcells, index paths, 66custom section index titles, 81information about sections, 68-69

RootViewController classbehavior, 49-51Note Collector application, configuring,

192-195renaming, 195

RootViewController code, 21-22RootViewController.h file, 166RootViewController.m method, 159rows

loading, 62table views, 65-67

rules, 41Delete Rule, 36, 46object validation, 5relationships, 4

running applications, 20

Ssafe fault-free methods, 236-237sample applications, Note Collector, 187-188saveContext method, 20save: method, 46savePerson: method, 171saving

contexts, 42-43edited strings, 207managed objects, fetching, 44-45objects, 43strings, editing, 207

screens, iPhone applications, 26Search Bars, adding, 139-141Search Display Controllers, adding, 130-141searching

predicates, modifying, 136-139support files, 149

sectional table views, 65sectionIndexTitleForSectionName: method,

81-82sections

customizing, returning index titles, 81Format Specifiers, 118headers, 68

index titles, 81information about, returning, 68-69modifying, 70NSFetchedResultsController, 235sorting, 170table views, 65-67

selectinginstruments, 246key paths in Xcode 3, 124

serialization, objects, 10setCurrentPerson: method, 177, 182setRelationshipKeyPathsForPrefetching:

method, 234sets

dictionaries, 9predicates, 129-130

setter methodsimplementation, 91transient properties, adding, 110-111

Simulator, 21, 252Size Inspector, 212sizes, fetching, 231sort descriptors, 45, 74sorting

fetching, 113properties, 113sections, 170troubleshooting, 269-270years, 159

specifyingcaching, 84classes, 30conditions, predicates, 126entities, 24inverse relationships, 36properties, 114

speed, optimizing, 224SQL (Structured Query Language), 4, 10, 130SQLDebug argument, configuring, 228SQLite, 4, 10

BLOBs (Binary Large OBjects), 238data store, 224-227

stacksformatting, 17-20initializing, 253

startup, troubleshooting, 254-255state management, 5statements, predicates, 117. See also

predicatesstorage, 41

binary data, 27-28databases, 10

resetting contexts, managed objects282

data store types, 224-230fetch requests in data models, 120incompatibility, 145persistent stores, 105

String attribute, 35String Programming Guide, 118strings

comparing, 124-126editing, saving, 207first responders, configuring, 206predicates, creating, 118-120substituting, 119

Structured Query Language. See SQLsubclasses. See also classes

customizing, 11managed objects, 54-59, 87-93NSFetchedResultsController, 80-85NSManagedObject, 191UIViewController, 210

sub-entities, abstract models, 189-190sub-predicates, 128. See also predicatessubstituting strings, 119substitution variables, 120-121summaries, migration, 155superCollection relationships, 192supplying pre-populated data stores, 217-219support

data stores, 224-230files, searching, 149managed object contexts, adding, 176undo, 174-175

synthesizing properties, 197, 204

TTable editor, 31tables

databases, 24. See also databasesjoin, 24SQL (Structured Query Language), 130views

applying, 46-54data source methods, 64-72NSFetchedResultsController, 62Random Dates application, 80rows, 65-67Search Display Controllers, 131sections, 65-67writing delegate methods, 95

tableView:didSelectRowAtIndexPath: method,199

Template application, 21

How can we make this index more useful? Email us at [email protected]

TemplateProjectAppDelegate.h interface file, 18templates

NSManagedObject subclass, 56projects, 252Xcode, 15-22

temporary object IDs, 265terminology, models, 24-25testAttribute attribute, 144testing

applications, 135MigrationTest.xcdatamodeld file, 144properties, 129

text, fields, 214textFieldShouldEndEditing method, 100textFieldShouldReturn: method, 205threading

collisions, 260-264multithreading, 257-258troubleshooting, 257-265

timestamps, viewing, 21titles

indexes, 68, 79, 81root view controllers, 168, 198

tokens, predicates, 118tools, Refractor (Xcode), 195tracking

changes, 13collections, 196managed objects, 164-168versions, 151

Transformable attribute, 34transformable attributes, 113-114Transient attributes, 32transient attributes, applying, 105-113triggering KVO (Key-Value-Observing) notifica-

tions, 91troubleshooting, 251

accessor methods, 266-267dictionaries, 129errors, 251-256faulting, 268-269iPhone OS 3.0, table views, 67managed objects, 265-269migration, 143-145not found errors, classes, 255-256objects, fetching, 269-270Random People application, 105results, 270startup, 254-255threading, 257-265

troubleshooting 283

typesattributes, 34data stores, 224-230instruments, 245

UUIColor properties, applying, 111-113UIViewController subclass, 210Undefined type, 34undo

actions, deleting, 181functionality, 163managers, configuring, 180notifications, registering, 180stacks, 5support, 174-175

undoManager property, 174uniquing, 14-15updating

interfaces, 165properties, managed objects, 168-170

userDidSaveStringEditorVC:... callback method,209

User Info area, 31userInfo key, 207

VvalidateValue:ForKey:error: method, 102validation

dates, 100errors, 103functionality, 98managed objects, 99-105, 171-173managed objects and data, 5prior to deletion, 104properties, 99-104requirements, 10

valuesmanaged objects

configuring, 168modifying, 179

propertiespre-loading, 235troubleshooting, 265-266

validation, 100variables

environment, 226instances, NSFetchedResultsController, 73predicates, 120-122substitution, 120

versioning, 143multiple data model, 145-148tracking, 151

Versioning area, 31viewDidLoad method, 50, 74, 96, 168viewing

Add button, 50cells, 193collections, 195-202iPhone applications, 26note editors, 215notes, 210-217RandomDate objects, 52-53raw data files, 200-202timestamps, 21view controllers, 167

viewscontrollers

adding outlets to, 164creating, 203-210as first responders, 174generating, 166initializing, 176, 198multiple, 163viewing, 167

tablesapplying, 46-54data source methods, 64-72NSFetchedResultsController, 62. See

also NSFetchedResultsControllerRandom Dates application, 80rows, 65-67sections, 65-67writing delegate methods, 95

viewWillDisappear: method, 168, 181

WWebObjects, 3WillChange method, 69willSave message, 110windows

Edit Scheme, 226New Project, 16

writing delegate methods, 95

Xxcdatamodeld bundles, 146Xcode, 5

Add (+) button, 31arguments, 228Calcuccino, 7

types284

consoles, 252contextual menus for attributes, 106Data Modeler, 10, 16-18. See also Data

Modelers (Xcode)applying, 28-37describing entities, 23-24editing fetch requests, 121

Data Model Inspector, 30key paths, selecting, 124migration summaries, 155MoneyWell, 6-7Refractor tool, 195templates, 15-22

XML (Extensible Markup Language), 4

YyearOfBirth attribute, 156years, sorting, 159

Zzeros, iPhone OS 3.0, troubleshooting table

views, 67

How can we make this index more useful? Email us at [email protected]

zeros, iPhone OS 3.0, troubleshooting table views 285