Pro Core Data for iOS Data Access and Persistence Engine for iPhone, iPad, and iPod touch Second Edition ■ ■ ■ Michael Privat and Robert Warner i Pro Core Data for iOS: Data Access and Persistence Engine for iPhone, iPad, and iPod touch Second Edition Copyright © 2011 by Michael Privat and Robert Warner All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-3656-6 ISBN-13 (electronic): 978-1-4302-3657-3 Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. President and Publisher: Paul Manning Lead Editor: Steve Anglin Development Editors: Matthew Moodie and Douglas Pundick Technical Reviewer: Robert Hamilton Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Morgan Ertel, Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Tom Welsh Coordinating Editor: Jennifer L. Blackwell Copy Editor: Mary Behr Compositor: MacPS, LLC Indexer: SPi Global Artist: SPi Global Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. For information on translations, please e-mail [email protected], or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to http://www.apress.com/source-code/. To my loving wife, Kelly, and our children, Matthieu and Chloé. —Michael Privat To my beautiful wife, Sherry, and our wonderful children: Tyson, Jacob, Mallory, Camie, and Leila. —Rob Warner Contents at a Glance Contents .............................................................................................................. v About the Authors ............................................................................................... x About the Technical Reviewer ........................................................................... xi Acknowledgments ............................................................................................ xii Introduction ..................................................................................................... xiii ■Chapter 1: Getting Started ............................................................................... 1(cid:2) ■Chapter 2: Understanding Core Data ............................................................. 27(cid:2) ■Chapter 3: Storing Data: SQLite and Other Options ....................................... 59(cid:2) ■Chapter 4: Creating a Data Model ................................................................ 111(cid:2) ■Chapter 5: Working with Data Objects ........................................................ 133(cid:2) ■Chapter 6: Refining Result Sets ................................................................... 187(cid:2) ■Chapter 7: Tuning Performance and Memory Usage ................................... 209(cid:2) ■Chapter 8: Versioning and Migrating Data .................................................. 253(cid:2) ■Chapter 9: Managing Table Views Using a Fetched Results Controller ....... 285(cid:2) ■Chapter 10: Using Core Data in Advanced Applications .............................. 307(cid:2) Index ............................................................................................................... 367 iv Contents Contents at a Glance .......................................................................................... iv(cid:2) About the Authors ............................................................................................... x(cid:2) About the Technical Reviewer ........................................................................... xi(cid:2) Acknowledgments ............................................................................................ xii(cid:2) Introduction ..................................................................................................... xiii ■Chapter 1: Getting Started ............................................................................... 1(cid:2) (cid:2) What Is Core Data? ................................................................................................................................................. 1 (cid:2) History of Persistence in iOS ................................................................................................................................... 2 (cid:2) Creating a Basic Core Data Application .................................................................................................................. 3 (cid:2) Understanding the Core Data Components ........................................................................................................ 3 (cid:2) Creating a New Project ...................................................................................................................................... 5 (cid:2) Running Your New Project ................................................................................................................................. 6 (cid:2) Understanding the Application’s Components ................................................................................................... 9 (cid:2) Fetching Results .............................................................................................................................................. 10 (cid:2) Inserting New Objects ...................................................................................................................................... 13 (cid:2) Initializing the Managed Context ..................................................................................................................... 14 (cid:2) Adding Core Data to an Existing Project ............................................................................................................... 16 (cid:2) Adding the Core Data Framework .................................................................................................................... 16 (cid:2) Creating the Data Model .................................................................................................................................. 19 (cid:2) Initializing the Managed Object Context .......................................................................................................... 22 (cid:2) Summary .............................................................................................................................................................. 25 ■Chapter 2: Understanding Core Data ............................................................. 27(cid:2) (cid:2) Core Data Framework Classes .............................................................................................................................. 27 (cid:2) The Model Definition Classes ........................................................................................................................... 30 (cid:2) The Data Access Classes ................................................................................................................................. 38 (cid:2) Key-Value Observing ........................................................................................................................................ 43 (cid:2) The Query Classes ........................................................................................................................................... 44 (cid:2) How the Classes Interact ...................................................................................................................................... 47 (cid:2) SQLite Primer ................................................................................................................................................... 53 (cid:2) Reading the Data Using Core Data ................................................................................................................... 55 (cid:2) Summary .............................................................................................................................................................. 57 v ■ CONTENTS ■Chapter 3: Storing Data: SQLite and Other Options ....................................... 59(cid:2) (cid:2) Visualizing the User Interface ............................................................................................................................... 60 (cid:2) Using SQLite as the Persistent Store .................................................................................................................... 63 (cid:2) Configuring the One-to-Many Relationship ...................................................................................................... 67 (cid:2) Building the User Interface .............................................................................................................................. 69 (cid:2) Configuring the Table ....................................................................................................................................... 72 (cid:2) Creating a Team ............................................................................................................................................... 72 (cid:2) The Player User Interface ................................................................................................................................. 81 (cid:2) Adding, Editing, and Deleting Players .............................................................................................................. 84 (cid:2) Seeing the Data in the Persistent Store ........................................................................................................... 89 (cid:2) Using an In-Memory Persistent Store ................................................................................................................... 92 (cid:2) Creating Your Own Custom Persistent Store ........................................................................................................ 94 (cid:2) Initializing the Custom Store ............................................................................................................................ 95 (cid:2) Mapping Between NSManagedOBject and NSAtomicStoreCacheNode ........................................................... 98 (cid:2) Serializing the Data ........................................................................................................................................ 101 (cid:2) Using the Custom Store ................................................................................................................................. 106 (cid:2) What About XML Persistent Stores? .............................................................................................................. 107 (cid:2) Summary ............................................................................................................................................................ 110 ■Chapter 4: Creating a Data Model ................................................................ 111(cid:2) (cid:2) Designing Your Database .................................................................................................................................... 111 (cid:2) Relational Database Normalization ................................................................................................................ 112 (cid:2) Using the Xcode Data Modeler ............................................................................................................................ 113 (cid:2) Viewing and Editing Attribute Details ............................................................................................................ 119 (cid:2) Viewing and Editing Relationship Details ....................................................................................................... 120 (cid:2) Using Fetched Properties ............................................................................................................................... 121 (cid:2) Creating Entities .................................................................................................................................................. 123 (cid:2) Creating Attributes .............................................................................................................................................. 125 (cid:2) Creating Relationships ........................................................................................................................................ 127 (cid:2) Name ............................................................................................................................................................. 128 (cid:2) Destination and Inverse ................................................................................................................................. 129 (cid:2) Transient ........................................................................................................................................................ 129 (cid:2) Optional .......................................................................................................................................................... 129 (cid:2) To-Many Relationship .................................................................................................................................... 130 (cid:2) Count (Minimum and Maximum) .................................................................................................................... 130 (cid:2) Delete Rule ..................................................................................................................................................... 130 (cid:2) Summary ............................................................................................................................................................ 131 ■Chapter 5: Working with Data Objects ........................................................ 133(cid:2) (cid:2) Understanding CRUD ........................................................................................................................................... 133 (cid:2) Creating the Shape Application Data Model .................................................................................................. 137 (cid:2) Building the Shape Application User Interface .............................................................................................. 145 (cid:2) Enabling User Interactions with the Shapes Application ............................................................................... 154 (cid:2) Generating Classes ............................................................................................................................................. 156 (cid:2) Modifying Generated Classes ............................................................................................................................. 164 (cid:2) Using the Transformable Type ............................................................................................................................ 169 (cid:2) Validating Data .................................................................................................................................................... 173 (cid:2) Custom Validation .......................................................................................................................................... 175 (cid:2) Invoking Validation ......................................................................................................................................... 179 vi ■ CONTENTS (cid:2) Default Values ................................................................................................................................................ 179 (cid:2) Undoing and Redoing .......................................................................................................................................... 180 (cid:2) Undo Groups .................................................................................................................................................. 181 (cid:2) Limiting the Undo Stack ................................................................................................................................. 181 (cid:2) Disabling Undo Tracking ................................................................................................................................ 182 (cid:2) Adding Undo to Shapes .................................................................................................................................. 182 (cid:2) Summary ............................................................................................................................................................ 185 ■Chapter 6: Refining Result Sets ................................................................... 187(cid:2) (cid:2) Building the Test Application .............................................................................................................................. 187 (cid:2) Creating the Org Chart Data ........................................................................................................................... 188 (cid:2) Reading and Outputting the Data ................................................................................................................... 191 (cid:2) Filtering ............................................................................................................................................................... 192 (cid:2) Expressions for a Single Value ....................................................................................................................... 193 (cid:2) Expressions for a Collection ........................................................................................................................... 194 (cid:2) Comparison Predicates .................................................................................................................................. 195 (cid:2) Compound Predicates .................................................................................................................................... 198 (cid:2) Subqueries ..................................................................................................................................................... 200 (cid:2) Aggregating ........................................................................................................................................................ 203 (cid:2) Sorting ................................................................................................................................................................ 204 (cid:2) Returning Unsorted Data ................................................................................................................................ 204 (cid:2) Sorting Data on One Criterion ........................................................................................................................ 205 (cid:2) Sorting on Multiple Criteria ............................................................................................................................ 206 (cid:2) Summary ............................................................................................................................................................ 207 ■Chapter 7: Tuning Performance and Memory Usage ................................... 209(cid:2) (cid:2) Building the Application for Testing .................................................................................................................... 209 (cid:2) Creating the Core Data Project ...................................................................................................................... 210 (cid:2) Creating the Data Model and Data ................................................................................................................. 213 (cid:2) Creating the Testing View .............................................................................................................................. 215 (cid:2) Building the Testing Framework .................................................................................................................... 218 (cid:2) Adding the Testing Framework to the Application ......................................................................................... 220 (cid:2) Running Your First Test .................................................................................................................................. 222 (cid:2) Faulting ............................................................................................................................................................... 223 (cid:2) Firing Faults ................................................................................................................................................... 224 (cid:2) Faulting and Caching ..................................................................................................................................... 225 (cid:2) Refaulting ....................................................................................................................................................... 225 (cid:2) Building the Faulting Test .............................................................................................................................. 226 (cid:2) Taking Control: Firing Faults on Purpose ....................................................................................................... 229 (cid:2) Prefetching .................................................................................................................................................... 231 (cid:2) Caching ............................................................................................................................................................... 233 (cid:2) Expiring ............................................................................................................................................................... 236 (cid:2) Memory Consumption .................................................................................................................................... 236 (cid:2) Brute-Force Cache Expiration ........................................................................................................................ 236 (cid:2) Expiring the Cache Through Faulting ............................................................................................................. 237 (cid:2) Uniquing .............................................................................................................................................................. 237 (cid:2) Improve Performance with Better Predicates ..................................................................................................... 241 (cid:2) Using Faster Computers ................................................................................................................................ 241 (cid:2) Using Subqueries ........................................................................................................................................... 242 vii ■ CONTENTS (cid:2) Analyzing Performance ....................................................................................................................................... 245 (cid:2) Launching Instruments .................................................................................................................................. 245 (cid:2) Understanding the Results ............................................................................................................................. 249 (cid:2) Summary ............................................................................................................................................................ 251 ■Chapter 8: Versioning and Migrating Data .................................................. 253(cid:2) (cid:2) Versioning ........................................................................................................................................................... 254 (cid:2) Lightweight M8igrations ..................................................................................................................................... 257 (cid:2) Migrating a Simple Change ............................................................................................................................ 258 (cid:2) Migrating More Complex Changes ................................................................................................................. 259 (cid:2) Renaming Entities and Properties .................................................................................................................. 260 (cid:2) Creating a Mapping Model .................................................................................................................................. 262 (cid:2) Understanding Entity Mappings ..................................................................................................................... 263 (cid:2) Understanding Property Mappings ................................................................................................................ 264 (cid:2) Creating a New Model Version That Requires a Mapping Model ...................................................................2 66 (cid:2) Creating a Mapping Model ............................................................................................................................. 270 (cid:2) Migrating Data .................................................................................................................................................... 276 (cid:2) Running Your Migration ................................................................................................................................. 277 (cid:2) Custom Migrations .............................................................................................................................................. 278 (cid:2) Making Sure Migration Is Needed .................................................................................................................. 280 (cid:2) Setting Up the Migration Manager ................................................................................................................. 281 (cid:2) Running the Migration ................................................................................................................................... 282 (cid:2) Summary ............................................................................................................................................................ 284 ■Chapter 9: Managing Table Views Using a Fetched Results Controller ....... 285(cid:2) (cid:2) Understanding NSFetchedResultsController ....................................................................................................... 285 (cid:2) The Fetch Request ......................................................................................................................................... 286 (cid:2) The Managed Object Context ......................................................................................................................... 286 (cid:2) The Section Name Key Path ........................................................................................................................... 286 (cid:2) The Cache Name ............................................................................................................................................ 287 (cid:2) Understanding NSFetchedResultsController Delegates ...................................................................................... 287 (cid:2) Using NSFetchedResultsController ..................................................................................................................... 288 (cid:2) Implementing NSFetchedResultsController ........................................................................................................ 288 (cid:2) Implementing the NSFetchedResultsController .................................................................................................. 293 (cid:2) Implementing the NSFetchedResultsControllerDelegate Protocol ...................................................................... 298 (cid:2) Indexing Your Table ....................................................................................................................................... 298 (cid:2) Responding to Data Change ........................................................................................................................... 302 (cid:2) Summary ............................................................................................................................................................ 305 ■Chapter 10: Using Core Data in Advanced Applications .............................. 307(cid:2) (cid:2) Creating an Application for Note and Password Storage and Encryption ........................................................... 307 (cid:2) Setting Up the Data Model ............................................................................................................................. 309 (cid:2) Setting Up the Tab Bar Controller .................................................................................................................. 310 (cid:2) Adding the Tab ............................................................................................................................................... 311 (cid:2) Incorporating NSFetchedResultsController into MyStash .............................................................................. 316 (cid:2) Creating the Interface for Adding and Editing Notes and Passwords ............................................................3 22 (cid:2) Splitting Data Across Multiple Persistent Stores ................................................................................................ 335 (cid:2) Using Model Configurations ........................................................................................................................... 336 (cid:2) Adding Encryption ............................................................................................................................................... 340 (cid:2) Persistent Store Encryption Using Data Protection ........................................................................................ 340 viii ■ CONTENTS (cid:2) Data Encryption .............................................................................................................................................. 342 (cid:2) Sending Notifications When Data Changes ......................................................................................................... 347 (cid:2) Registering an Observer ................................................................................................................................ 348 (cid:2) Receiving the Notifications ............................................................................................................................ 349 (cid:2) Seeding Data ....................................................................................................................................................... 349 (cid:2) Adding Categories to Passwords ................................................................................................................... 350 (cid:2) Creating a New Version of Seeded Data ........................................................................................................ 353 (cid:2) Error Handling ..................................................................................................................................................... 353 (cid:2) Handling Core Data Operational Errors .......................................................................................................... 355 (cid:2) Handling Validation Errors ............................................................................................................................. 357 Handling Validation Errors in MyStash ........................................................................................................... 360 (cid:2) Summary ............................................................................................................................................................ 365 Index ............................................................................................................... 367 ix