5

I have a function like this:

func foobar() {
  let targetThread = Thread.current

  DispatchQueue.main.async {
    UIView.animate(withDuration: 0.5, animations: {
      // Code I need to run on the main thread
    }, completion: {
      // Code I want to run on targetThread -- HOW?
    }
  }
}

How do I execute code from targetThread? Thanks.

7ball
  • 2,183
  • 4
  • 26
  • 61
  • it will be better you create a new thread instead using currently running thread. and keep an access to it outside the method, and start it when you call this method. class var current: Thread Returns the thread object representing the current thread of execution. – Deepak Singh Mar 07 '17 at 20:07
  • Why do you need to run code on a specific thread? You shouldn't have to and this is discouraged. You probably want to `DispatchQueue.global().async` in the completion block and run the code there, but let us know why you want the code to run on a target thread? – Alistra Mar 07 '17 at 20:15
  • 2
    It's very common to want to call delegates on the same thread that they called on. Unfortunately gcd doesn't really support that. NSObject's performSelector:onThread can be used, but it's not a very clean API. I've seen programs have their own performBlock:onThread method that uses performSelector:onThread. – EricS Mar 07 '17 at 20:30

1 Answers1

6

DispatchQueues are not threads. You'll note there is no way to get the current DispatchQueue the way you can get the current thread. If you just want to run code somewhere that isn't the main thread, you can use:

DispatchQueue.global().async { ... }

If you really want to target your specific thread, you have two choices.

The first is you can use NSObject's perform(_:on:with:waitUntilDone:) (or one of the related methods) and pass the NSThread you've gotten. There isn't enough context in your question to say if this will work for you or to give an example, but you can search.

The second is to re-work your code that is starting all of this to use an NSOperationQueue, so foobar() would be run in an operation on the NSOperationQueue and then in your completion for the animation, you'd schedule another NSOperation to run on the same Operation Queue. You could also do this using dispatch queues directly: i.e. create your own dispatch queue, dispatch foobar, then dispatch back to your queue from main when the animation completes.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222