2

I have 3 examples of code:

1: self.perform(#selector(self.endRefreshing), with: nil, afterDelay: 0)

2: self.perform(#selector(self.endRefreshing))

3: DispatchQueue.main.asyncAfter(deadline: .now()) { self.endRefreshing() }

What is the difference in their execution if everything happens in the main thread?

Leonid
  • 21
  • 2
  • `self.perform` will not change the thread, it will be triggered in the same thread on which `self.perform` was called, where as `DispatchQueue.main.asyncAfter` will switch the execution to main thread and will ensure that `self.endRefreshing()` is called on main thread, where as `self.perform` and `self.performWith` the only difference is, it allows you pass additional info to call like if you wanna pass the object as a part of self.perform trigger example `UIGestureRecognizer` or `UIButton` also provides additional customization capability like adding a delay before actually triggering – Sandeep Bhandari Mar 22 '21 at 08:45
  • Perhaps needless to say, but that last example can be simplified to `DispatchQueue.main.async { self.endRefreshing() }`. And you would do that if you are not currently on the main queue. If you were already on the main queue, you would probably just call `endRefreshing()` directly. You really don’t see the `perform` variations nowadays. It’s an older API that predates GCD that app developers don’t use much anymore. – Rob Mar 23 '21 at 05:15
  • Related discussion https://stackoverflow.com/q/19500820/1271826 or https://stackoverflow.com/q/5512641/1271826. All those answers are using the old `dispatch_async` style API (which is replaced by this newer `DispatchQueue` API), but the observations are still largely relevant... – Rob Mar 23 '21 at 05:42

0 Answers0