objective-c callbacks

来源:互联网 发布:js身份证算法验证 编辑:程序博客网 时间:2024/05/16 06:32

In a real-world applications, there needs to be an object that waits for events like mouse movements, touch events, timers, and network activity. On Mac Os x and iOS, this object is an instance of NSRunLoop. Run Loop 等待消息发生,然后发送消息到另外一个目标。

当消息发生的时候,run loop会引起一个回调函数发生。在Objective-c 中共有三种形式的回调函数:

(1)Target-action: 在等待开始的时候,you say "When x happens, send this particular message to that particular object." The object receiving the message is thetarget. The selector for the message is theaction.

(2)Helper objects: 等待开始前,you say "Here is a helper object that conforms to your protocol. Send it messages when things happen."Helper objectsare often known as delegates anddata sources.

(3)Notifications: There is an object notification center. Before the wait begins, you say to the notification center "This object is waiting for these sorts of notifications. When on e of those notifications arrives, send the object this message". When x happens, an object posts a notification to the notification center, and the center forwards it on to your object.


Which to use?

(1) Objects that do just one thing (like NStimer) use target-action.

(2) Objects that have more complicated lives (like an NSURLConnection) use helper objects, and the most common type of helper object is the delegate.

(3) Objects that might need to trigger callbacks in several other objects (like NSTimeZone) usenotifications. 比如当Mac上的时区发生改变时, 你程序里的许多对象可能需要知道这种改变。


原创粉丝点击