微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

selector与函数指针

    源自:《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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐