0

I have the following method:

- (void) broadcastSelector:(SEL)selector {
    for (id listener in [self listeners]) {
        if([listener respondsToSelector:@selector(selector)]) {
            [listener performSelector:@selector(selector)];
        }
    }
}

And I'm calling it in the following way:

[self broadcastSelector:@selector(onLoginRequestStarted)];   

And that doesn't work. My confusion is the following:

If I hardcode the selector in the method, like the following:

- (void) broadcastSelector:(SEL)selector {
    for (id listener in [self listeners]) {
        if([listener respondsToSelector:@selector(onLoginRequestStarted)]) {
            [listener performSelector:@selector(onLoginRequestStarted)];
        }
    }
}

everything works fine. So I'm assuming something is wrong with how I call the method, or how I define the parameter.

jscs
  • 63,694
  • 13
  • 151
  • 195
Tamby Kojak
  • 2,129
  • 1
  • 14
  • 25

1 Answers1

3

I think you're double-encoding the selector inside your loop. Try this:

if([listener respondsToSelector:selector]) {
    [listener performSelector:selector];
}
Mike Mertsock
  • 11,825
  • 7
  • 42
  • 75
  • If I do that I get a warning that says `PerformSelector may cause a leak because its selector is unknown`. Should I ignore that? – Tamby Kojak May 12 '14 at 20:23
  • 1
    Interesting, I've never had to actually write this type of code so I didn't know about this warning. I think [this other answer](http://stackoverflow.com/a/20058585/795339) provides an explanation, and an alternative implementation that avoids the warning. – Mike Mertsock May 12 '14 at 20:27
  • This warning makes me want to know the original intent of your code. Could you use one of the messaging mechanisms provided by Apple, such as notification center or KVO? – Mike Mertsock May 12 '14 at 20:29