Offloading Tasks with Operations and GCD

In the previous chapter, you learned how to use Instruments to measure your app's performance. Measuring performance is a vital skill in discovering slow code or memory leaks. You saw that sometimes it's easy to fix slow code and increase performance by fixing a small programming error. However, the fix isn't always that easy.

An example of code that is very hard to make fast is networking code. When you fetch data from the network, you do this asynchronously. If networking code was not asynchronous, the execution of your app would halt until the network request is finished. This means that your app would freeze for a couple of seconds if the network is slow.

Another example of relatively slow code is a data file from the app bundle and decoding the raw data into an image. For small images, this task shouldn't take as long as a networking request, but imagine loading a couple of larger images. Decoding a large amount of data would take long enough to significantly slow down an app's scrolling performance, or render the interface unresponsive for longer than you should be comfortable with.

Making code run asynchronously is not very hard if you do it through dispatch queues. In Objective-C and early versions of Swift, this was mostly known as GCD or Grand Central Dispatch, and the methods you'd use to interact with GCD were ugly. Nowadays, you use the DispatchQueue class, and the methods you interact with are much cleaner.

This chapter will teach you how to make use of dispatch queues to write asynchronous code that can perform slow operations off the main thread, meaning that they don't block the interface while they're running. Once you've got the hang of using dispatch queues, you will abstract some of your asynchronous code into Operations, so it's possible to reuse them.

This chapter covers the following topics:

  • Writing asynchronous code with dispatch queues
  • Creating reusable tasks with operations

By the end of this chapter, you'll be able to enhance your apps by optimizing your code for asynchronous programming. You'll also be able to abstract specific tasks into Operations to make your app more straightforward to understand and maintain.