Early Praise for Core Data in Swift Marcus’s books have long been my go-to recommendation for people who want to learn about Core Data. With new information for beginners and experts alike, they are a great insight into how you should be using Core Data and the features that it offers. ➤ Daniel Tomlinson Senior software engineer, Rocket Apps Ltd. Marcus has a profound understanding of Core Data, and this book describes not only the basics of working with Core Data, but also how to do so in a performant manner, with explanations and examples. This is an indispensable reference, alongside Apple’s documentation, and one that will quickly make Core Data your go-to persistence mechanism. You’ll be able to deal with anything that comes up with confidence. ➤ Abizer Nasir Lead developer, Jungle Candy Software Ltd. A compelling book, packed with useful information. ➤ Steven Oxley Senior engineer, Social Native We've left this page blank to make the page numbers the same in the electronic and paper books. We tried just leaving it out, but then people wrote us to ask about the missing pages. Anyway, Eddy the Gerbil wanted to say “hello.” Core Data in Swift Data Storage and Management for iOS and OS X Marcus S. Zarra The Pragmatic Bookshelf Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic books, screencasts, and audio books can help you and your team create better software and have more fun. Visit us at https://pragprog.com. The team that produced this book includes: Jacquelyn Carter (editor) Potomac Indexing, LLC (index) Liz Welch (copyedit) Gilson Graphics (layout) Janet Furlow (producer) For sales, volume licensing, and support, please contact [email protected]. For international rights, please contact [email protected]. Copyright © 2016 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-68050-170-4 Encoded using the finest acid-free high-entropy binary digits. Book version: P2.0—July 2016 Contents Introduction . . . . . . . . . . . . . ix 1. Before We Begin . . . . . . . . . . . . 1 Test Application 1 The Storyboard 2 The Recipe List 4 The Recipe Detail 6 The Edit Workflow 7 Ready for Core Data 10 2. Under the Hood . . . . . . . . . . . . 13 Introducing the NSManagedObjectModel 15 Integrating with the NSPersistentStoreCoordinator 17 Adding the NSManagedObjectContext 20 Working with NSManagedObject Instances 21 Building an NSFetchRequest 28 NSSortDescriptor 31 Wrapping Up 32 3. iOS: NSFetchedResultsController . . . . . . . 33 How to Use the NSFetchedResultsController 33 Under the Hood of the NSFetchedResultsController 40 Building Our Own: MSZContextWatcher 42 Wrapping Up 45 4. Versioning and Migration . . . . . . . . . 47 Some Maintenance Before We Migrate 48 A Simple Migration 50 The Difference Between Light and Heavy Migrations 53 A Heavy/Manual Migration 54 Contents • vi Fundamentals of Core Data Versioning 61 Wrapping Up 64 5. Performance Tuning . . . . . . . . . . . 65 Persistent Store Types 65 Optimizing Your Data Model 67 Fetching 71 Faulting 74 Access Patterns 77 Wrapping Up 78 6. Threading . . . . . . . . . . . . . 79 Threading and Core Data 80 Working on the Main Queue 81 Working off the Main Queue 83 Interqueue Communication 83 Parent/Child NSManagedObjectContext Design 86 Export Operation 87 Import Operation 93 Asynchronous Saving 98 Debug Concurrency Checking 101 Wrapping Up 102 7. Bulk Changes . . . . . . . . . . . . 103 Running with Scissors 103 Doing Bulk Updates 104 Notifying the Application of Changes 107 Bulk Deletes 109 Things to Consider When Using the Bulk Change APIs 110 Wrapping Up 111 8. Network Operations . . . . . . . . . . 113 The Problem and the Approach 113 The Solution 114 Accessing the Network Operations 121 Wrapping Up 121 9. Using Core Data with iCloud . . . . . . . . 123 Introducing the UIManagedDocument 124 Direct NSManagedObjectContext to iCloud 129 Consuming Changes from iCloud 132 Under the Hood 133 Contents • vii Migrating an Existing Application 135 Desktop iCloud Integration 138 Issues with Data Quantities 140 Sharing Data Between iOS and OS X 140 Wrapping Up 142 10. Adding a Desktop Foundation . . . . . . . . 143 Our Application 143 Our Application Design 144 Sharing the Data Model 144 Building the Controller Layer 145 Building the User Interface 147 Adding a Splash of Code 152 Wrapping Up 155 11. Bindings, KVC, and KVO . . . . . . . . . 157 Key Value Coding 158 Key Value Observing 159 Cocoa Bindings and Core Data 161 Other Interface Elements That Use KVO, KVC, and Core Data 164 Wrapping Up 168 12. Spotlight, Quick Look, and Core Data . . . . . . 169 Integrating with Spotlight 170 Integrating with Quick Look 183 Putting It All Together 188 Wrapping Up 188 Index . . . . . . . . . . . . . . 191 Introduction It’s amazing to realize that as of the writing of this book, Core Data is over 12 years old. That’s an incredible number when you consider that it’s more powerful and more popular today than it has ever been. For a framework, that’s pretty spectacular. In this book we discuss Core Data and work with the framework from the perspective of Swift. Swift is a young language and has a lot of growing yet to do, but its popularity can’t be denied. It’s clear that Swift is important to Apple and therefore should be equally important to developers who work on Apple’s platforms. Is This Book for You? If you plan on writing an application that saves data to disk, then you should take a very long look at Core Data. Whether you’re focusing on the desktop or the iPhone, Core Data is the most efficient solution to data persistence. A good way to confirm that you know enough Cocoa to benefit from this book is to take a look at Chapter 1, Before We Begin, on page 1. You should find it dense, but every step should be familiar to you. What Is Core Data? In the simplest terms, Core Data is an object graph that can be persisted to disk. But just like describing a man as a “bag of mostly water,” that description hardly does Core Data justice. If you have worked with Interface Builder (specifically on OS X), you know that it effectively removes a third of the coding from the Model-View-Controller (MVC) design pattern. With Interface Builder, developers don’t need to spend countless hours writing and rewriting their user interface to make sure that it’s pixel perfect. Instead, they simply drag and drop the elements in the IDE, bind them together, and call it done. report erratum • discuss