Returning result of executing a selector on another thread in Swift or Objective-C

问题内容:

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 result value?

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

let val = 3
perform(#selector(MyClass.calc(val:)), on: myThread, with: val, waitUntilDone: true, modes: [RunLoopMode.commonModes.rawValue])

问题评论:

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 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
3 hours ago
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)
1
Just out of curiosity: how come, you cannot use GCD and have to stick to run loops?

原文地址:

https://stackoverflow.com/questions/47753452/returning-result-of-executing-a-selector-on-another-thread-in-swift-or-objective

添加评论

友情链接:蝴蝶教程