Avoiding Ten Big Mistakes iOS Developers Make with Core Data
Core Data is an Apple framework for Mac and iOS, which primarily allows you to persist data. For a lot of people, it has a steep learning curve. This means that without the right approach it can be difficult to understand, let alone master. This leads developers to make common mistakes that can otherwise be easily avoided. This article outlines each mistake, and then goes on to explain how you can avoid making them yourself.
1. Not Knowing the Key Terminology
Learning Core Data is an essential part of being an iOS Developer. Most iOS Apps couldn’t exist without it. As you poke around the Internet searching for tutorials to learn Core Data, it’s easy to become intimidated by all the new terminology. In fact, most articles assume you already know the terminology, and yet if you don’t, you’re in for a world of confusion. So let’s get the key terminology straight. Here’s a high level cheat-sheet you can use for reference as you learn Core Data, which shows the key terms:
Term |
Also Known As |
What is it? |
Managed Object Model |
The Model, Data Model, Schema or Object Graph |
A file containing the definition of an application's data structure. |
Persistent Store |
The Store or Database |
A file containing application data that will survive even when the device is turned off. |
Managed Object |
|
Some data from a Persistent Store. |
Managed Object Context |
The Context, or MOC |
An area in memory where you interact with Managed Objects. |
Persistent Store Coordinator |
The Coordinator |
An object that mediates between Persistent Store(s) and Managed Object Context(s) as per the Managed Object Model. |
Entity |
|
Defines Managed Objects. |
Attribute |
|
A property of an Entity. |
Relationship |
|
Joins Entities. |
Fetch Request |
|
A way of retrieving Managed Objects from a Persistent Store. |
Predicate |
Filter |
A way of limiting the managed objects that a Fetch Request will return. |
Sort Descriptor |
|
A way of ordering the managed objects that a Fetch Request will return. |
There are plenty more terms you’ll come across, however those are the fundamental ones to focus on first.
2. Ignoring Core Data Altogether
When a technology has a reputation for being difficult to learn, you might be tempted to ignore it. This is particularly true when you’re short on time and you just want to get the app out the door!
A common alternative to Core Data for persisting application data is to use XML Property Lists. Although property lists might make your life easier today, they could come back to bite you later. You see, whenever you edit a property list, the changes are atomic. This means that even minor changes require that the whole file be loaded into memory, and then the whole file be written back to disk when it is saved. As the data grows, the application will slow. If, however, you’re using Core Data with an SQLite database, changes can be made incrementally instead. This keeps memory usage low, which in turn ensures that the app remains responsive and prevents memory pressure crashes. Essentially, Core Data is more scalable than property lists because it supports using a database as a persistent store.
Scalability isn’t the only benefit of using Core Data. The ability to organize data into entities structured with relationships is where more of its true power lies. For example, consider the following entity that represents a task:
The Task entity contains a name and subtask_name attribute. When a managed object is created from this Task entity, it will have a name and subtask_name property. Without relationships, this data model supports only one subtask. Now consider the following entities:
The line with the double-headed arrow indicates a to-many relationship from the Task entity to the Subtask entity. This means that a task can now have multiple subtasks, not to mention that reference to the parent task can be obtained through the inverse relationship! This flexibility is not only more convenient, but also saves space in the database because the parent task name only has to be stored once.
If you wanted to get really advanced and enable support for tasks to have subtasks of subtasks, what then? Consider the re-architected Task entity below:
The model now supports an unlimited depth of subtasks because the Task entity is related to itself!
The scalability and flexibility of Core Data is only scratching the surface of its benefits. Core Data not only leverages the benefits of a relational database, you don’t even have to write any SQL to use it! Core Data takes on that responsibility for you, and optimizes the generated SQL for you automatically. I haven’t even begun to dive into the myriad of the other value-add that you get for free, such as model versioning, migration, validation, change management and iCloud synchronization, to name a few. If there’s any iOS framework that’s worth investing your time in, it’s Core Data.
3. Not Using Model Versioning and Migration
If you’ve ever edited a managed object model, odds are you’ve come across the following error:
"The model used to open the store is incompatible with the one used to create the store."
When you create a persistent store, it is based on a specific managed object model. If the structure of the model ever changes, then the persistent store must be updated to match. If you don’t do this, the store will be incompatible and won’t open anymore. If your customers are using stores based on a model you have since edited without versioning, your app is destined to crash. To ensure the model migration process works, you need to ensure you’re careful to add a model version before editing the model. As a side note, some changes such as attribute defaults, validation rules, and fetch request templates can be modified without consequence.
4. Using Model Versioning and Migration Too Much
Once developers come to terms with how simple it is to maintain versions of a managed object model, some have a tendency to overuse it. This can lead to an overcomplicated version history if you add a version for every change, which only slows down the model migrations. The thing to remember here is that it’s only the persistent store on customer devices that matters.
Before you release a Core Data app to the App Store, you can ignore versioning and edit the model as many times as you like. To avoid the “the store is incompatible” error, simply delete the app from your development device and run it from Xcode again. This will deploy a new persistent store using the updated model, and the crash will be resolved. Once you’ve released version 1 of your model to the App Store, however, all of your customers will have a version 1 persistent store. From that point on you must add a new version if you update the model.
Let’s assume for example that your customers are using model version 1. While developing an updated app, you’ve added model versions 2, 3 and 4. Instead of releasing model versions 2, 3 and 4, use this trick to reduce version history:
- Delete the contents of model 2
- Copy the contents of model 4 to model 2
- Set model 2 as the current model
- Delete model 3 and model 4
Of course, you’ll need to consider how the entities in model 1 map to the now more radical model 2, particularly if you’re not using lightweight migration. For a full step-by-step guide to model versioning and migration, look no further than a complete chapter excerpt from “Learning Core Data for iOS”. Share the love and tweet it to your friends!
5. Leaving Everything in Memory
As you focus on functionality and features, it’s easy to forget the less glamorous topics like keeping memory usage low. The temptation to release an application before a good round of performance testing, especially when you’re on a deadline, can sometimes be too much. Luckily it’s pretty easy to put steps in place to help keep memory usage low.
When you work with managed objects, you do so in memory using a managed object context. Once you’re finished with managed objects, you should remove them from memory by calling one of the following NSManagedObjectContext instance methods:
- Use reset to remove all managed objects from a context
- Use refreshObject:mergeChanges and pass NO to remove a specific object from a context
Using either of those methods will ensure that unused objects aren’t floating around wasting space. To increase your visibility of the number of objects in a context, log the results of [[context registeredObjects] count] to the debug console regularly.
6. Designing a Slow Managed Object Model
If you’re storing large objects such as photos, audio or video, you need to be very careful with your model design. The key point to remember is that when you bring a managed object into a context, you’re bringing all of its data into memory. If large photos are within managed objects cut from the same entity that drives a table-view, performance will suffer. Even if you’re using a fetched results controller, you could still be loading over a dozen high-resolution images at once, which isn’t going to be instant. To get around this issue, attributes that will hold large objects should be split off into a related entity. This way the large objects can remain in the persistent store and can be represented by a fault instead, until they really are needed. If you need to display photos in a table view, you should use auto-generated thumbnail images instead.
7. Not Preloading Data
When you ship a new model version with an updated application, you need to be careful not to accidentally ship a default data store based on an old model. If you do, the update will probably crash on launch for some (if not all) users. This threat can deter developers from shipping a default data store at all!
If default data is included with an application, it becomes easier to learn to use. The easier a program is to use, the more likely it is that people will continue to use it. The longer people use an application, the more chance that word about the application will spread, thus increasing sales potential.
To avoid crashing updates while still providing default data, you need a good testing strategy. In addition, you also need a strong understanding of exactly what model versions and stores you’ve shipped to the App Store. You should deploy an untouched App Store version of the application to your device, add some data, and then test the upgrade process thoroughly.
8. Not Using Multiple Contexts
At a minimum, a Core Data implementation should have one context operating on the main thread. The user interface also operates on the main thread, so any slowdowns to the main thread will impact application responsiveness. While it is easier to use only one context, performance issues can creep in unless your data set is extremely small. For example, if you wanted to generate photo thumbnails or import some data, the application would appear to lock up for the duration of these processes.
Since iOS 5, managing multiple contexts has become a lot easier. You can now configure a context hierarchy and run some contexts in the foreground and others in the background. By positioning a background context as a parent of a foreground context, you can implement background save. By positioning a background context as a child of a foreground context, you can implement an import context that automatically updates the user interface as objects are imported.
9. Not Understanding the Limitations of iCloud Integration
Since iOS 7, Core Data integration with iCloud has become much easier to implement. A key limitation of iCloud, however, is that its data is constrained to one iCloud account. Because iCloud accounts are deeply intertwined with many aspects of user devices, it is not practical or recommended to share iCloud accounts. This means that iCloud cannot be used to collaborate. For example, assume a husband and wife wanted to contribute to the same shopping list. This isn’t currently possible with iCloud.
Beyond account limitations, iCloud has no support for ordered relationships and also limits your lightweight model migration. Thinking outside the box, if you’re interested in gathering analytical stats about your apps usage, you might consider using a Backend-as-a-Service (BaaS) instead. On that note, using a BaaS will also enable synchronization with other platforms, such as Android or HTML5.
10. Integrating with iCloud Without Respect to Existing Customer Data
Because iCloud integration with Core Data is now easier to implement with iOS 7, many developers are confident enough to support it in their apps. Historically it has been too unstable to trust with precious customer data. This has resulted in many existing apps having only local stores, such as my own ‘Teamwork’ app, which I swear I’ll update one of these days!
One of the key simplifications of iCloud under iOS 7 is the introduction of the fallback store. This store allows a seamless transition between iCloud accounts and the toggling of iCloud Documents and Data. Users can start using an app with iCloud even if they have no network connection, and they will be none the wiser as their data is merged with iCloud once the network is available. While all of this is fantastic, the existing pre-iOS 7 local store full of your customer’s data should not be forgotten. If you just turn on iCloud, you’ll be using a different store and you’ll need to merge the user’s local data with iCloud. Before you attempt to merge the user’s local data, you’ll need to check:
- Is the user signed in to iCloud?
- Does the user want to use iCloud with this application?
- Does the user want to merge their local data with iCloud?
If the answer to any of those questions is no, the app should be positioned to handle a different answer in the future. If all answers are yes, then you’ll need to manage the seeding process of the user’s local data to iCloud. When users have multiple devices with local data, things can get really interesting. In that case, you’ll need to consider a de-duplication strategy, too.
Conclusion
If there’s any iOS framework that’s worth investing your time in, it’s Core Data. Knowing this solid technology pays dividends, and once you’ve picked it up you’ll never look back. If you’re interested in learning Core Data, consider my new book, Learning Core Data for iOS. This iOS 7 based book takes you on the complete journey from knowing nothing about Core Data to producing “Grocery Dude,” which is available for free on the App Store today. Everything is explained in succinct detail so you can apply what you’ve learned straight away. I’ve put a chapter summary up here. Happy coding!
You might also like:
By Tim Roadley
Learn More
By Jesse Feiler
Learn More