Home > Articles > Mobile Application Development & Programming

Avoiding Ten Big Mistakes iOS Developers Make with Core Data

This article highlights common mistakes developers make with Core Data. It also touches on Core Data’s benefits, terminology, versioning, migration, performance, and iCloud integration pitfalls and how you can avoid them.
Like this article? We recommend

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:


Learning Core Data for iOS: A Hands-On Guide to Building Core Data Applications

 

 

Learning iCloud Data Management: A Hands-On Guide to Structuring Data for iOS and OS X

 

 

Xcode 5 Start to Finish: iOS and OS X Development

 

 


InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020