Search code examples
objective-cselectornsinvocation

Passing a selector name as a method parameter


I'm writing a custom helper method that will get used a lot and return several buttons. Each button will of course have its own target selector when pressed, and I want to pass the selector as a parameter into this method so the returned button has the specified selector.

But I'm not sure how to pass a selector as a method parameter. Something like this:

-(returnedInstance)someMethod:(WhatClass?*)selectedFunction{

[SomeClassWithASelectorParameter method:whatever selector:@selector(selectedFunction)];

}

where selectedFunction is a parameter passed into the method.

I tried making WhatClass?* a NSString and also SEL but that resulted in:

[NSInvocation invocationWithMethodSignature:]: method signature argument cannot be nil


Solution

  • Why don't you just pass a SEL? i.e. a selector. Like so:

    -(returnedInstance)someMethod:(SEL)selectedFunction{
        [SomeClassWithASelectorParameter method:whatever selector:selectedFunction];
    }
    

    Alternatively, NSSelectorFromString:

    -(returnedInstance)someMethod:(NSString*)selectedFunction{
        [SomeClassWithASelectorParameter method:whatever selector:NSSelectorFromString(selectedFunction)];
    }