Selector Projector
Because Objective-C is a dynamic language, it resolves methods at runtime, not at compile time. This setup provides a subtle but powerful mechanism: You can pass methods as parameters to other methods.
Selectors are special variables that identify which method implementation to use for an object instance. The Objective-C runtime uses internal data structures to match a message's selector to the code that gets executed.
Tip
If you've used other languages, you might want to think of a selector as a dynamic function pointer. The selector's name automatically points to the right function and adapts to whichever class it's used with.
This behavior lets you implement polymorphism in Objective-C. If you have three classes named Circle, Triangle, and Square, you can send a selector for a draw method to instances of each of these classes, resulting in different implementations for drawing the shape being executed.
Every selector is defined with a type of SEL. You can assign the selector variable with one of two methods. At compile time, you can use a compiler directive to create the value:
SEL mySelector = @selector(moreAwesomeThanEver);
At runtime, you can use a function that takes a single NSString parameter and looks up the selector:
SEL mySelector = NSSelectorFromString("moreAwesomeThanEver");The mySelector variable now contains a shortcut for the –moreAwesomeThanEver message. And here's where it gets interesting: You can use that variable to execute the method. So instead ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access