Multithreading in iOS| Difference between GCD and NSOperation

Basics of concurrency in iOS.

Image for post
Image for post
override func viewDidLoad() {super.viewDidLoad()doSomeTimeConsumingTask() // takes 5 seconds to respond
tableView.reloadData()
}
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
override func viewDidLoad() {super.viewDidLoad()DispatchQueue.global(qos:.userInteractive).async {
self.doSomeTimeConsumingTask() // takes 5 seconds to respond
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}

NSOperation and Grand Central Dispatch

Reference: StackOverflow, Cocoacasts, nhipster

  • NSOperation and NSOperationQueue are high-level Objective-C classes.

Benefits of NSOperation

  • You can Pause, Cancel, Resume an NSOperation . With Grand Central Dispatch, you no longer have control or insight into the execution of that task. The NSOperation API is more flexible in that respect, giving the developer control over the operation's life cycle.
  • You can set up a dependency between two NSOperations . This is a powerful concept that enables developers to execute tasks in a specific order. An operation is ready when every dependency has finished executing.
  • Can monitor the state of an operation or operation queue. ready, executing or finished.
  • The NSOperation and NSOperationQueue classes have a number of properties that can be observed, using KVO (Key-Value Observing). This is another important benefit if you want to monitor the state of an operation or operation queue.
  • You can specify the maximum number of queued operations that can run simultaneously

“ when you want more control over queue (all above mentioned) use NSOperation and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use GCD.

Enjoy!!

If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!

You can follow me on Medium for fresh articles. Also, connect with me on LinkedIn.

iOS and tvOS developer, dreamer, photographer 🤨