2

Suppose I wanted to invoke a selector calc on a specific thread. Meaning it's the case where I really must use a run loop (can't use GCD).

calc performs some calculation and produces a result value, suppose an Int.

It is easy to pass a parameter to the selector method.

What would be a good way to retrieve the result value?

@objc function calc(val: Any) {
    guard let val = val as? Int else { return }
    let result = val * 10
    ...
}

// ... somewhere in a calling object
let val = 3
perform(#selector(MyClass.calc(val:)), on: myThread, with: val, waitUntilDone: true, modes: [RunLoopMode.commonModes.rawValue])
// ... how to get the result of calc() ?
Denis Zubkov
  • 137
  • 10
  • https://stackoverflow.com/questions/313400/nsinvocation-for-dummies ? Then performing the invocation on antoher thread is another question, but could be an hint on how pass params, etc. – Larme Dec 11 '17 at 12:57
  • @Larme I am not sure NSInvocation works with run loops? Note the requirement from the supplied code that the function is run on a specific (another) thread while the calling thread is suspended (waiting for completion). – Denis Zubkov Dec 11 '17 at 13:08
  • As @Larme mentioned in the comments, I would also suggest using `NSInvocation`. Returning the value from `calc` would be done by a closure thats handed into the `calc` function, like: `@objc func calc(val: Any, calculationFinishedHandler:(result:Int)->()) { ... calculationFinishedHandler(result:result)}` If you need more details (or sample code), I could elaborate it (but will take a while) – Andreas Oetjen Dec 11 '17 at 13:35
  • 1
    Just out of curiosity: how come, you cannot use GCD and have to stick to run loops? – Dávid Pásztor Dec 11 '17 at 14:15
  • @DávidPásztor That is due to some esoteric legacy C library code (math stuff) that periodically misbehaves when executed from different threads. Yes, I have tried standard sync methods (mutex, semaphore) but still no stable outcome. It must be a purposefully allocated single thread that is looking after the code. Thus neither GCD nor NSInvocation work here. It's one of those tricky case where one can't go by the book. – Denis Zubkov Dec 12 '17 at 02:20
  • `NSInvocation` has in the actual sense nothing do do with threads. It is just a means to execute a function dynamically - which has been the only way to do so for functions with more than two parameters before blocks / closures were invented. You could then use the `NSInvocation` to execute this on a dedicated thread. – Andreas Oetjen Dec 12 '17 at 09:00

0 Answers0