0

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

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
johnbakers
  • 24,158
  • 24
  • 130
  • 258

2 Answers2

4

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)];
}
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
  • Hehe thanks :-). That's one of my favourite things about SO - racing others to the answer whilst maintaining a complete, concise answer. – mattjgalloway Feb 23 '12 at 09:08
  • as my question indicated, I tried using SEL with no luck; getting the error I posted. – johnbakers Feb 23 '12 at 09:09
  • 1
    @andrewx - Yes, but did you try what I've posted? Both should work. Notice there's no `@selector(...)` in either. – mattjgalloway Feb 23 '12 at 09:10
  • actually, looks like it was merely my syntax that was wrong. i'll test some more and come back in a bit! – johnbakers Feb 23 '12 at 09:11
  • @andrewx - Sounds entirely plausible given you were trying with `@selector(...)`. That's never going to be the right way to do it if you're passing in the selector. – mattjgalloway Feb 23 '12 at 09:12
1

You want to use SEL, and when you refer to it, you don't have to use selector:

-(returnedInstance)someMethod:(SEL)selectedFunction{

    [SomeClassWithASelectorParameter method:whatever selector:selectedFunction];

}
yuji
  • 16,695
  • 4
  • 63
  • 64