Chapter 6
Threading

Multithreading is one of the great double-edged swords of programming. If it’s done correctly, it can be a real boon to your application; done incorrectly, it leads to strange, unreproducible errors in the application. Multithreading has a tendency to polarize developers: they either swear that it’s necessary for any application to perform properly or declare it’s to be avoided at all costs. The truth, of course, is somewhere in the middle. Multithreading is a vital piece of the overall performance puzzle. While adding more threads won’t make your application automatically faster, it can make it “feel” faster to the user. That perception is what we’re going to focus on in this chapter.

It’s a common misconception among developers that the point of adding threads to an application is to improve performance. While there’s no argument that proper threading support can improve performance in an application, treating threading like a silver bullet is a sure way to disaster.

Threading should be introduced to an application as part of the design process, whenever there’s a situation where the application can or should be doing more than one thing. Any situation during the application design where an operation is needed but the user doesn’t need to wait on that operation is a perfect situation for an additional thread.

Here are some common operations that fall into this category:

And the list goes on. In addition to these concepts there’s the concept of anticipating the user and what data the user is going to want next. If, for example, you’re developing a news application, it makes sense to load the full news articles, images, videos, and so forth while the user is still scrolling through the list of articles. Ideally your application will have the data loaded and ready to display before the user selects it.

When an application can correctly predict what data a user is going to want to see before the user requests it, that application reaches a whole new level in user experience.

The purpose of adding threads to your application is to improve user experience by offloading work the user doesn’t need to be blocked by, as well as predictively load data before the user needs it.

With that goal for threading in mind, let’s look at how to use Core Data in a multithreaded environment.