Operation and OperationQueue on SWIFT !

Operation and OperationQueue on SWIFT !

The solution is to move work off the main thread via concurrency. Concurrency means that your application executes multiple streams (or threads) of operations all at the same time. This way the user interface stays responsive as you’re performing your work.

One way to perform operations concurrently in iOS is with the Operation and OperationQueue classes. In this tutorial, you’ll learn how to use them! You’ll start with an app that doesn’t use concurrency at all, so it will appear very sluggish and unresponsive. Then, you’ll rework the app to add concurrent operations and provide a more responsive interface to the user!

Tasks, Threads and Processes
Before going further, there are a few technical concepts you need to understand. Here are some key terms:

Task: a simple, single piece of work that needs to be done.
Thread: a mechanism provided by the operating system that allows multiple sets of instructions to operate at the same time within a single application.
Process: an executable chunk of code, which can be made up of multiple threads.

Operation vs. Grand Central Dispatch (GCD)
You may have heard of Grand Central Dispatch (GCD). In a nutshell, GCD consists of language features, runtime libraries, and system enhancements to provide systemic and comprehensive improvements to support concurrency on multi-core hardware in iOS and macOS. If you’d like to learn more about GCD, you can read our Grand Central Dispatch Tutorial.

Operation and OperationQueue are built on top of GCD. As a very general rule, Apple recommends using the highest-level abstraction, then dropping down to lower levels when measurements show this is necessary.

Here’s a quick comparison of the two that will help you decide when and where to use GCD or Operation:

GCD is a lightweight way to represent units of work that are going to be executed concurrently. You don’t schedule these units of work; the system takes care of scheduling for you. Adding dependency among blocks can be a headache. Canceling or suspending a block creates extra work for you as a developer!
Operation adds a little extra overhead compared to GCD, but you can add dependency among various operations and re-use, cancel or suspend them.

One way to perform operations concurrently in iOS is with the NSOperation and NSOperationQueue classes. What’s a poor developer to do? The solution is to move work off the main thread via concurrency. Concurrency means that your application executes multiple streams (or threads) of operations all at the same time – this way the user interface can stay responsive as you’re performing your work.

SAMPLE CODE-1

SAMPLE CODE-2