Swift: What’s the best way of invoking a callback selector?

“M” asks: “What’s the best way of invoking a callback selector? I’m overriding an ObjC method that takes a target/selector/argument combo, and performSelector is not available in Swift”

Answer: Use NSThread to perform the selector on an ObjC class instance.

class MyClass : NSObject {
    func hello() {println("Hello")}
}

var instance = MyClass()
var selector = Selector("hello")
NSThread(target: instance, selector: selector, object: nil).start()

Warning: this doesn’t run on the main thread. (You can use main() instead of start() off label to achieve this but it seems iffy and undocumented.) Of course, a much better answer is to use closures wherever possible.

Comments are closed.