A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn’t do anything. It simply identifies a method. compiler makes sure that selectors are unique.
What makes a selector useful is that (in conjunction with the runtime) it acts like a dynamic function pointer that, for a given name, automatically points to the implementation of a method appropriate for whichever class it’s used with.
Getting a Selector
At compile time, you use the compiler directive @selector.
SEL aSelector = @selector(methodName);
|
SEL aSelector = NSSelectorFromString(@"methodName");
|
SEL aSelector = @selector(run);
|
[aDog performSelector:aSelector];
|
[anAthlete performSelector:aSelector];
|
[aComputerSimulation performSelector:aSelector];
|
At runtime, you use the NSSelectorFromString function, where the string is the name of the method:
You use a selector created from a string when you want your code to send a message whose name you may not know until runtime.
Compiled selectors are of type SEL. There are two common ways to get a selector:
You can invoke a method using a selector with performSelector: and other similar methods.
(You use this technique in special situations, such as when you implement an object that uses the target-action design pattern. Normally, you simply invoke the method directly.)
This comment has been removed by a blog administrator.
ReplyDelete