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.
In Objective-C, selector has two meanings. It can be used to refer simply to the name of a method when it's used in a source-code message to an object. It also, though, refers to the unique identifier that replaces the name when the source code is compiled. Compiled selectors are of type SEL .
A selector is an identifier which represents the name of a method. It is not related to any specific class or method, and can be used to describe a method of any class, whether it is a class or instance method. Simply, a selector is like a key in a dictionary.
Selectors are usually used when you want to define a callback mechanism. The most common use case for selectors in Cocoa is with controls, such as buttons. A UIButton
is very generic, and as such has no idea what should happen when the button is pressed. Before you can use one, you need to tell it what method should be run when the button is pressed. This is done as follows:
[myButton addTarget:self
action:@selector(myButtonWasPressed)
forControlEvents:UIControlEventTouchUpInside];
- (void)myButtonWasPressed {
// Do something about it
}
Then, when the button is pressed, the button will call the selector on the target we passed it. With this mechanism, you don't need to subclass a button every time you want it to call some of your own code. Instead, UIButton
itself has a generic mechanism for dispatching to any code you choose. (Okay, technically, it's the superclass UIControl
that's providing the dispatch mechanism.)
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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With