Objective-C Language SEL


Example

Selectors are used as method identifiers in Objective-C.

In the example below, there are two selectors. new and setName:

Person* customer = [Person new];
[customer setName:@"John Doe"];

Each pair of brackets corresponds to a message send. On the first line we send a message containing the new selector to the Person class and on the second line we send a message containing the setName: selector and a string. The receiver of these messages uses the selector to look up the correct action to perform.

Most of the time, message passing using the bracket syntax is sufficient, but occasionally you need to work with the selector itself. In these cases, the SEL type can be used to hold a reference to the selector.

If the selector is available at compile time, you can use @selector() to get a reference to it.

SEL s = @selector(setName:);

And if you need to find the selector at runtime, use NSSelectorFromString.

SEL s NSSelectorFromString(@"setName:");

When using NSSelectorFromString, make sure to wrap the selector name in a NSString.

It is commonly used to check if a delegate implements an optional method.

if ([self.myDelegate respondsToSelector:@selector(doSomething)]) {
    [self.myDelegate doSomething];
}