ObjC中的消息传递机制小结
引子
本文是学习ObjC中的消息传递机制的一篇小结小结
KVO
- One to Many: 一个对象的value changes 可以被多个对象监听
- 但recipient 必须知道 sender 的生命周期,因为必须在sender对象deallcated之前unregister the observer
- 在Core Data 中使用要注意 Core Data的Faulting 机制,因为managed对象变成fault时也会引发KVO监听
Notifications
- Broadcast: sender 和 recipient 不需要知道彼此的生命周期,低相关性;
- 可以通过
userInfo
传递数据
Delegation
通过函数参数传递数据
松耦合,使用广泛
Delegation is very flexible and straightforward communication pattern if you only need to communicate between two specific objects.
紧耦合不适用 ,容易造成循环引用?
Blocks
- 潜在隐患:
if the sender needs to retain the block and cannot guarantee that this reference will be a nilled out, the every reference to self from within the block becomes a potential retain cycle.
如1
2
3self.myTableView.selectionHandler = ^void(NSIndexPath *selectedIndexPath) {
// handle selection ...
};而 如下就不会,原因是operation 执行完后会立即释放
1 | self.queue = [[NSOperationQueue alloc] init]; |
Target-Action
- Target-Action is the typical pattern used to send messages in response to user-interface events.
- A limitation of target-action-based communication is that the messages sent cannot carry any custom payloads.
- 非常松耦合,target 和 action 不用知道对方的存在,甚至target=nil ,Action 会沿着响应链一直传递直到找到响应者。On iOS, each control can even be associated with multiple target-action pairs.