Junior — Middle
How can asynchronous task execution be implemented in iOS using Grand Central Dispatch?
sobes.tech AI
Answer from AI
Grand Central Dispatch (GCD) is a low-level API in iOS for managing asynchronous task execution using queues.
To perform a task asynchronously with GCD, you can use the dispatch_async function, which places a block of code into a specified queue and immediately returns control, without blocking the current thread.
Example usage:
DispatchQueue.global(qos: .background).async {
// Long operation, e.g., data loading
let data = fetchDataFromNetwork()
DispatchQueue.main.async {
// Update UI on the main thread
self.updateUI(with: data)
}
}
Here:
DispatchQueue.global(qos: .background)is a global background queue for executing heavy tasks.asyncis for asynchronous execution of the block.- After completing the background work, switch to the main thread to update the UI.
Thus, GCD makes it easy to perform tasks in the background without blocking the interface, and to return to the main thread for UI updates.