OperationQueue.main vs DispatchQueue.main

AppsDev picture AppsDev · Nov 23, 2016 · Viewed 15.4k times · Source

When you need to perform something on the main thread in the completion block of a networking task or an operation, which of these ways to get it would be the most appropriate and why?:

  • OperationQueue.main.addOperation
  • DispatchQueue.main.async

Answer

MrMage picture MrMage · Nov 23, 2016

For details on the differences between the two types of queue, see Lion's answer.

Both approaches will work. However, NSOperation is mostly needed when more advanced scheduling (including dependencies, canceling, etc.) is required. So in this case, a simple

DispatchQueue.main.async { /* do work */ }

will be just fine. That would be equivalent to

dispatch_async(dispatch_get_main_queue(), ^{ /* do work */ });

in Objective-C, which is also how I would do it in that language.