Are selectors in Objective-C just another way to send a message to an object?

lampShade picture lampShade · Aug 22, 2010 · Viewed 7k times · Source

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.

Answer

BJ Homer picture BJ Homer · Feb 26, 2012

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.)