Selectors

Selectors are a unique type for the Cocoa platform, and are used to represent a method name for the purposes of passing it on to APIs and have the method with the given name called back at a later time.

They are represented by the SEL type, and the Cocoa base libraries provide functions for converting a string to SEL and back, with the NSSelectorFromString and NSStringFromSelector APIs available in Foundation.

The Elements languages also provide a syntax for declaring selector literals, using the selector (Oxygene) or __selector (C#) keywords, and a string-like syntax in Swift:

var s: SEL := selector(buttonClicked:);
someObject.performSelector(s);
SEL s = __selector(buttonClicked:);
someObject.performSelector(s)
let s: SEL = "buttonClicked:";
someObject.performSelector(s)

Note that selector literals (and NSSelectorFromString) expect the selector in Objective-C Runtime naming convention, with colons in place of each parameter.

In Swift, the selector literal syntax is indistinguishable from a regular string literal. Context of the literal (such as the type of the variable or parameter it is being assigned to) is used to distinguish between strings and selectors.

Using the selector literal syntax will cause the compiler to perform checks if the specified selector is valid and known, and a warning will be emitted if a selector name is provided that does not match any method known to the compiler. This provides extra safety over using the NSSelectorFromString function.

See Also

Read More

Read more about Selectors at these external links: