What are the most effective ways of achieving concurrency in iOS?


In iOS development, there are several techniques available to achieve concurrency, You will see different approaches in this article along with some examples. You will learn about Grand Central Dispatch and NSOperationQueue techniques with examples.

What is concurrency in iOS?

In iOS applications, you can adopt the ability to run the multiple tasks or threads simultaneously by the operating system. In iOS, primarily you achieve concurrency through the use of Grand Central Dispatch (GCD) and NSOperationQueue

Developers can prevent blocking the main thread, which updates the user interface, by leveraging concurrency. Instead, they can carry out background activities concurrently, enhancing the app's overall performance.

Grand Central Dispatch (GCD)

In iOS, macOS, and other Apple operating systems, Grand Central Dispatch (GCD) is a low-level C API that offers effective, system-wide control of concurrent processes. It is constructed on top of the dispatch queues and thread management primitives at a lower level.

Dispatch queues are a tool used by GCD to organize tasks. A data structure called a dispatch queue is used to store a list of tasks that must be carried out. Worker threads can perform tasks that have already been added to a queue.

GCD provides several types of queues, including

  • Main Dispatch Queue − This queue performs the tasks on the main queue. That's why most of the time we use this for updating the user interface. A queue like this is used most of the time by iOS users to reload table data, change the content of a label, or change the state of a button.

  • Global Dispatch Queues − These queues can be used to perform all types of tasks at once. These queues are shared throughout the entire system. Also, these don't need the main queue to perform any tasks.

  • Custom Dispatch Queues − In order to manage tasks carefully, developers can create custom queues. You can create custom queues to execute specific tasks or groups of tasks at once.

Here are some examples of how to use GCD in iOS −

Executing a task on the main queue

This is the syntax of executing the task on the main queue asynchronous.

DispatchQueue.main.async {
   // write the code here to update the user interface.
}

Executing a task on a global queue

This is the syntax of executing the task on the background thread asynchronous.

DispatchQueue.global(qos: .background).async {
   // Write the code to perform a background task
}

Executing a task on a custom queue

This is the syntax of executing the task on a custom queue asynchronous.

let customQueue = DispatchQueue(label: "com.example.myqueue")
customQueue.async {
   // write the code to perform the task
}

let customQueue = DispatchQueue(label: "com.example.myqueue")
customQueue.sync {
   // write the code to perform the task
}

It's important to remember that GCD offers additional features like barriers, groups, and semaphores. You can wait for several activities to finish, synchronize tasks, and more using these tools. The priority of the task, whether it should be carried out on the main thread or a background thread, and how many resources it should receive are all indicated by the QoS (Quality of Service) classes.

NSOperationQueue or OperationQueue

The higher-level Objective-C interface NSOperationQueue is used in iOS to control concurrent tasks. Built on top of Grand Central Dispatch (GCD), it offers extra features including automatic cancellation and interdependence between processes. It is accessible in Swift as OperationQueue.

A queue of operations that are carried out concurrently or serially is known as an NSOperationQueue or OperationQueue. An operation is a single piece of work that can be carried out concurrently or serially, like a method call. The queue allows operations to be added, and depending on their priority and dependencies, the queue will choose the order in which they are executed.

Here are some examples of how to use NSOperationQueue in Swift −

Creating an operation queue

In this step, you will create a custom operation queue to perform tasks.

let operationQueue = OperationQueue()
Add an operation to the queue:
let operation = BlockOperation {
   // code to perform the task
}
operationQueue.addOperation(operation)

Add multiple operations to the queue

In this step, you will add different operations to the queue to perform them.

let operation1 = BlockOperation {
   // code to perform task 1
}
let operation2 = BlockOperation {
   // code to perform task 2
}
operationQueue.addOperations([operation1, operation2], waitUntilFinished: false)

Add dependencies between operations

In this step, you can see how to add dependency between operations in the queue.

let operation1 = BlockOperation {
   // code to perform task 1
}
let operation2 = BlockOperation {
   // code to perform task 2
}
operation2.addDependency(operation1)
operationQueue.addOperations([operation1, operation2], waitUntilFinished: false)

Setting the maximum number of concurrent operations

operationQueue.maxConcurrentOperationCount = 2

You should note here that NSOperationQueue is more powerful and advanced compared to DispatchQueue. This approach provides you with more control over your operations such as you can set the priority, pause or cancel them, and you can manage the dependencies between operations. Overall, you don't have a specific reason to choose DispatchQueue, you can use NSOperationQueue.

NSThread

Swift thread creation and management in iOS are made possible by the class NSThread (Foundation framework). It should only be used when NSOperationQueue and GCD (Grand Central Dispatch) do not offer the required capabilities because it is a lower-level API.

A thread is a distinct "flow" of control through a programme that only follows one path of execution. The stack used to hold the execution state of each thread is unique to that thread.

Core Animation

A framework called Core Animation offers hardware-accelerated, high-performance animation. It may be used to make fluid animations for your iOS app because it is built on top of GCD.

Conclusion

You can perform multiple tasks or threads in a concurrent manner on the iOS operating system. This process is called concurrency. With iOS, you can implement and manage concurrency in your applications in a variety of ways. These approaches are GCD (Grand Central Dispatch), NSOperationQueue, NSThread, and more.

Concurrency is a necessity in iOS because it allows for the most efficient use of system resources and improved performance by allowing multiple processes to run simultaneously. This is in comparison to one at a time. Programmers can run background processes concurrently thanks to concurrency, as opposed to interrupting the main thread that is in charge of updating the user interface. This improves the app's overall performance.

Consider the overhead and potential issues that can arise from launching too many threads and poorly synchronizing access to shared resources, and use the strategy that is best for your app's specific requirements.

Updated on: 28-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements