Are selectors in objective - c just another way to send a message to an object? I really don't understand why or how to use them.
views:
66answers:
2At the most basic, yes, but you can change the message at runtime. For example:
SEL a = [selectorFactory getSelector];
[someOtherObject performSelector:a];
And then in selectorFactory.getSelector
:
if(foo == 1)
return @selector(thisSelector);
else
return @selector(thatSelector);
Coming from C#
or another similar language, you can use this to (loosely) simulate events much more easily than using NSNotification
s. For example, you could make a button class with two ivars, target
and selector
, and have the button perform the selector on the target when it's clicked (for example).
There's a lot more to selectors than that, though. Read more about them here:
They aren’t another way to send a message to an object, they’re the only way. For example, in [myView setValue:@"foo"]
, setValue:
is a selector. (Another, less convenient way of writing the same thing is objc_msgSend(myView, @selector(setValue:), @"foo")
.)
As Ian Henry says, you can use SEL
values to choose a selector at runtime instead of compile time. This is a fundamental technique in Cocoa; user interfaces are generally connected to controllers using target/action bindings, where the target is an object and the action is a selector. Normally you set this up in a nib, but you can also do it in code:
[myButton setTarget:myController];
[myButton setAction:@selector(buttonClicked:)]; // Clicking the button will now call [myController buttonClick:myButton].