1

I have to call method of a class. This method potentially exists or not. I'm looking for a solution from 2 hours. The following works without parameter sayHello()

I have the class :

class myClass: NSObject {
    func say(something:String){
        print("I say : \(something)")
    }

    func sayHello(){
        print("Hello")
    }
}

1st step : Create a selector from a string with a parameter

let selector = NSSelectorFromString("sayHello" ) 
let selectorWithParam = NSSelectorFromString("say:" ) 

2nd step : Test if the method exist

self.bot?.responds(to: selector)// true
self.bot?.responds(to: selectorWithParam) // false        

it doesn't work with a parameter!

Beside, i tried with the Swift3 #selector , but I found no way to enter a method from a string

Damien Romito
  • 9,801
  • 13
  • 66
  • 84

1 Answers1

1

The Swift method

func say(something:String)

is mapped to Objective-C as

- (void)sayWithSomething:(NSString * _Nonnull)something;

and therefore the correct selector would be

let selectorWithParam = NSSelectorFromString("sayWithSomething:" )

Using #selector is less error-prone:

let selectorWithParam = #selector(myClass.say(something:))
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks you, and how to create a `#selector` from a variable? `let myMethod = "sayWithSomething"` The method could be anything and I have to check if it exist before to call it – Damien Romito Dec 07 '16 at 16:30
  • @DamienRomito: You cannot use `#selector` with a variable. If you really need to create a selector dynamically from an arbitrary string then you can use only `NSSelectorFromString`. (It would be interesting to know *why* you need that.) – Martin R Dec 07 '16 at 17:12
  • The behaviour of my application depends on a customizable json. This json list methods to call. – Damien Romito Dec 07 '16 at 17:24
  • 1
    Note that this is potentially dangerous. What if the JSON contains a method name which happens to be a `NSObject(Protocol)` method (e.g. `release`). Calling that method on the object would cause memory corruption. –Anyway, you asked why your NSSelectorFromString does not work, and I have (hopefully) answered that. – Martin R Dec 07 '16 at 17:33
  • Yes, the better solution I found is to use a "switch case" to match the variable to the corresponding method. This way, isn't dangerous. Thank you Martin! Good luck for you Stackoverflow's quest ;) – Damien Romito Dec 07 '16 at 17:40