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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值