mercredi 16 novembre 2016

Swift selectors: how to construct instance referring to method with parameters?

I'm using Swift and Objective C's reflection to try to invoke a method, but the method accepts arguments and I can't work out how to construct an instance of Selector which refers to a method which accepts arguments.

Here is some sample code:

class Thing : NSObject {

    func doSomething() {
    }

    func doSomething(str :String) {
    }

}

extension Thing {

    func doSomethingElse(str :String) -> String {
    }

}

let t = Thing()

var selector = Selector("doSomething")
//selector = Selector("doSomething:")

if t.responds(to: selector) {
    t.perform(selector)
}

So I can invoke doSomething with no problem, but I cannot seem to create a Selector from a string which refers to doSomething(str :String).

Just in case it makes any difference, I'm ultimately attempting to invoke the extension method doSomethingElse.

How can I invoke Swift methods with arguments via reflection/selectors?

P.S. I'm aware that in general you're supposed to use #selector nowadays, but this won't work in my case because the method doSomething might not exist in the compiled code.





Aucun commentaire:

Enregistrer un commentaire