Core Data by Tutorials Core Data by Tutorials Fifth Edition Aaron Douglas, Matthew Morey and Pietro Rea Copyright ©2018 Razeware LLC. Notice of Rights All rights reserved. No part of this book or corresponding materials (such as text, images, or source code) may be reproduced or distributed by any means without prior written permission of the copyright owner. Notice of Liability This book and all corresponding materials (such as source code) are provided on an "as is" basis, without warranty of any kind, express of implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in action of contract, tort or otherwise, arising from, out of or in connection with the software or the use of other dealing in the software. Trademarks All trademarks and registered trademarks appearing in this book are the property of their own respective owners. raywenderlich.com 2 Core Data by Tutorials Dedications "To my husband, Mike, who puts up with all my weird quirks and supports all the things I do." — Aaron Douglas "To my amazing wife Tricia and my parents — Thanks for always supporting me." — Matthew Morey "To my wonderful wife Emily, my daughter Rose, and my parents. Thank you for always supporting me every step of the way." — Pietro Rea raywenderlich.com 3 Core Data by Tutorials About the Authors Aaron Douglas was that kid taking apart the mechanical and electrical appliances at five years of age to see how they worked. He never grew out of that core interest — to know how things work. He took an early interest in computer programming, figuring out how to get past security to be able to play games on his dad's computer. He's still that feisty nerd, but at least now he gets paid to do it. Aaron's interest in mobile software has been ever increasing since he got his first iOS app in Apple's App Store in 2009, Migraine Diary. He is with Automattic (WordPress.com, Akismet, SimpleNote) as a Mobile Maker. Other than software development, Aaron enjoys camping during the summer, taking his dogs for a walk around the neighborhood, and pretending to be a storm chaser while sitting at home. Follow him on Twitter as @astralbodies and on his blog at https://aaron.blog. Matthew Morey is an engineer, author, hacker, creator and tinkerer. As an active member of the iOS community and CTO at MJD Interactive he has led numerous successful mobile projects worldwide. When not developing apps he enjoys traveling, snowboarding, and surfing. He blogs about technology and business at matthewmorey.com. Pietro Rea is a senior software engineer at Upside Travel in Washington D.C. Pietro's work has been featured in the App Store across several categories: media, e-commerce, lifestyle and more. Having worked at Fortune 500 companies and venture-backed startups, Pietro has a passion for building apps users can't live without. You can find Pietro on Twitter as @pietrorea. raywenderlich.com 4 Core Data by Tutorials About the Editors Darren Ferguson is the technical editor for this book. He is an experienced software developer and works for M.C. Dean, Inc, a systems integration provider from North Virginia. When he's not coding, you'll find him enjoying EPL Football, traveling as much as possible and spending time with his wife and daughter. Find Darren on Twitter as @darren102. Chris Belanger is the editor of this book. Chris is the Editor-in-Chief for raywenderlich.com. He was a developer for nearly 20 years in various fields from e-health to aerial surveillance to industrial controls. If there are words to wrangle or a paragraph to ponder, he‘s on the case. When he kicks back, you can usually find Chris with guitar in hand, looking for the nearest beach. Twitter: @crispytwit. Rich Turton is the final pass editor of this book. Rich is an iOS developer for MartianCraft and long-time contributor to raywenderlich.com. When he's not in front of a computer he is usually trying to play the piano, trying to make fancy cocktails, or trying to play elaborate Lego games with his daughters. Sometimes all at the same time. About the Artist Vicki Wenderlich is the designer and artist of the cover of this book. She is Ray’s wife and business partner. She is a digital artist who creates illustrations, game art and a lot of other art or design work for the tutorials and books on raywenderlich.com. When she’s not making art, she loves hiking, a good glass of wine and attempting to create the perfect cheese plate. raywenderlich.com 5 Core Data by Tutorials Table of Contents: Overview Introduction ............................................................................. 11 Chapter 1: Your First Core Data App............................. 17 Chapter 2: NSManagedObject Subclasses .................. 38 Chapter 3: The Core Data Stack ...................................... 66 Chapter 4: Intermediate Fetching................................... 89 Chapter 5: NSFetchedResultsController................... 123 Chapter 6: Versioning & Migration .............................. 149 Chapter 7: Unit Testing ..................................................... 188 Chapter 8: Measuring & Boosting Performance..... 206 Chapter 9: Multiple Managed Object Contexts...... 239 Conclusion.............................................................................. 259 More Books You Might Enjoy ......................................... 260 raywenderlich.com 6 Core Data by Tutorials Table of Contents: Extended Introduction ............................................................................. 11 What you need.................................................................................................................... 12 Who this book is for.......................................................................................................... 13 How to use this book........................................................................................................ 13 What’s in store.................................................................................................................... 13 Source code and forums.................................................................................................. 14 Updates.................................................................................................................................. 15 License.................................................................................................................................... 15 About the cover.................................................................................................................. 16 Chapter 1: Your First Core Data App............................. 17 Getting started................................................................................................................... 18 Modeling your data........................................................................................................... 27 Saving to Core Data.......................................................................................................... 30 Fetching from Core Data................................................................................................ 34 Key points............................................................................................................................. 37 Chapter 2: NSManagedObject Subclasses .................. 38 Getting started................................................................................................................... 38 Modeling your data........................................................................................................... 41 Storing non-standard data types in Core Data...................................................... 45 Managed object subclasses........................................................................................... 46 Propagating a managed context.................................................................................. 51 Data validation in Core Data......................................................................................... 60 Tying everything up........................................................................................................... 63 Key points............................................................................................................................. 65 Chapter 3: The Core Data Stack ...................................... 66 Getting started................................................................................................................... 66 Rolling your own Core Data stack............................................................................... 67 The managed object model............................................................................................ 68 The persistent store.......................................................................................................... 68 raywenderlich.com 7 Core Data by Tutorials The persistent store coordinator................................................................................ 69 The managed object context......................................................................................... 70 The persistent store container..................................................................................... 71 Creating your stack object............................................................................................. 71 Modeling your data........................................................................................................... 74 Adding managed object subclasses............................................................................ 78 A walk down persistence lane...................................................................................... 81 Deleting objects from Core Data................................................................................ 85 Key points............................................................................................................................. 88 Chapter 4: Intermediate Fetching................................... 89 NSFetchRequest: the star of the show...................................................................... 89 Introducing the Bubble Tea app................................................................................... 91 Stored fetch requests....................................................................................................... 94 Fetching different result types..................................................................................... 98 Sorting fetched results.................................................................................................. 114 Asynchronous fetching................................................................................................. 117 Batch updates: no fetching required....................................................................... 119 Key Points.......................................................................................................................... 121 Chapter 5: NSFetchedResultsController................... 123 Introducing the World Cup app................................................................................. 124 It all begins with a fetch request............................................................................... 126 Grouping results into sections................................................................................... 133 “Cache” the ball................................................................................................................ 136 Monitoring changes....................................................................................................... 137 Inserting an underdog................................................................................................... 143 Key Points.......................................................................................................................... 147 Where to go from here?................................................................................................ 148 Chapter 6: Versioning & Migration .............................. 149 When to migrate.............................................................................................................. 149 The migration process................................................................................................... 150 Types of migrations........................................................................................................ 151 Getting started................................................................................................................. 152 raywenderlich.com 8 Core Data by Tutorials A lightweight migration................................................................................................ 153 Inferred mapping models............................................................................................. 155 A manual migration........................................................................................................ 160 A complex mapping model........................................................................................... 169 Migrating non-sequential versions.......................................................................... 176 A self-migrating stack.................................................................................................... 176 Testing sequential migrations.................................................................................... 186 Key points........................................................................................................................... 187 Chapter 7: Unit Testing ..................................................... 188 Getting started................................................................................................................. 189 Core Data stack for testing......................................................................................... 190 Asynchronous tests........................................................................................................ 196 Tests first............................................................................................................................ 198 Validation and refactoring........................................................................................... 202 Key points........................................................................................................................... 205 Where to go from here?................................................................................................ 205 Chapter 8: Measuring & Boosting Performance..... 206 Getting started................................................................................................................. 206 Measure, change, verify................................................................................................ 208 Fetching and performance.......................................................................................... 219 Key points........................................................................................................................... 237 Challenge............................................................................................................................ 238 Chapter 9: Multiple Managed Object Contexts...... 239 Getting started................................................................................................................. 240 Introducing SurfJournal............................................................................................... 240 Doing work in the background.................................................................................. 244 Editing on a scratchpad................................................................................................. 251 Key points........................................................................................................................... 257 Challenge............................................................................................................................ 258 Conclusion.............................................................................. 259 More Books You Might Enjoy ......................................... 260 raywenderlich.com 9 Core Data by Tutorials New to iOS or Swift?...................................................................................................... 260 Experienced iOS developer?....................................................................................... 262 Want to make games?.................................................................................................... 273 Want to learn Android or Kotlin?.............................................................................. 277 raywenderlich.com 10