Selectors

Selectors are internal representation of a method name in Objective-C. They are used to SELECT a method to execute for an object, it identifies the method.
Selectors let us treat a method as if it was independent entity, and separate the action from the object that needs to perform it. This is the basis of Target-Action design pattern and is an integral part of Objective-C dynamics typing system.
In Target-Action design pattern the object contains the necessary information to send a message to another object when an event occurs. For example, the button needs to notify the view controller that the button was clicked (touch event) and then the view controller can act upon this information. Button here has a target (to whom) and action method (what message should be sent).

Target-Action example
Target-Action example

Dynamic typing means that object can be sent a message that is not specified in its interface. This allows an object to capture a message and send it to a different object that can respond to this message appropriately. This is known as message forwarding or delegation.

- (void) objDisplay: (id) object
{
    [object displayInfo];
}

There are two ways to get the selector for a method name:

  • @selector() – convert a source-code method name to a selector
  • NSSelectorFromString() – convert a string to a selector

Both return a special data type SEL

Selector code example
Selector code example

Selectors can be executed on arbitrary object via performSelector: and related methods. When we are not sure if the target object defines the method, we should use respondsToSelector: check before trying to perform a selector.
Sample project with selectors and delegates is on Github.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s