源自:《cocoa设计模式》
Selectors identify the messages that are sent to Objective-C objects.They’re used by the receivers of messages to select which methods will be performed. Selectors provide much of the power, flexibility, and dynamism of the Objective-C language, and they’re used to implement other Cocoa design patterns. In particular, selectors are key to Cocoa’s implementation of the Notifications, Delegates,Targets and Actions, Invocations, and For- warding patterns. Using selectors, Cocoa objects can be asked to perform methods imme- diately or after arbitrary time delays. Delaying the performance of methods can be very handy and is sometimes used to keep a user interface responsive while long-running tasks complete, implement animation, or provide other time-based application features.
Selectors are an object-oriented substitute for C function pointers.A function pointer is a variable that stores the address of a compiled function. In the C programming lan- guage and languages derived from it like Objective-C and C++, compilers and linkers convert explicit function calls in program source code into machine language jumps to code at predetermined fixed addresses in memory.The conversion of code to fixed ad- dresses in sometimes called binding. Using a function pointer variable enables program- mers to postpone binding of a function call until the program is running. For example, the value of a function pointer might be partly determined by user input at runtime.The technique is sometimes called late-binding. Just like using function pointers can postpone specification of precisely what function will be called, using selectors can postpone speci- fication of precisely what message will be sent to an object.
What makes selectors more object-oriented than function pointers, and why are they used instead of function pointers?That’s a bit of a trick question because ultimately, Objective-C uses function pointers.The answer involves the implementation of Objective-C message sending as described in the “Solution” section of this chapter, but simply stated, selectors are used by objects to select which method is performed, and then the implementation of the selected method is accessed via a function pointer.The role of the object in the selection of a method is key to object orientation.