ObjC中的消息传递机制小结

引子

本文是学习ObjC中的消息传递机制的一篇小结小结

KVO

  1. One to Many: 一个对象的value changes 可以被多个对象监听
  2. 但recipient 必须知道 sender 的生命周期,因为必须在sender对象deallcated之前unregister the observer
  3. 在Core Data 中使用要注意 Core Data的Faulting 机制,因为managed对象变成fault时也会引发KVO监听

Notifications

  1. Broadcast: sender 和 recipient 不需要知道彼此的生命周期,低相关性;
  2. 可以通过userInfo传递数据

Delegation

  1. 通过函数参数传递数据

  2. 松耦合,使用广泛

    Delegation is very flexible and straightforward communication pattern if you only need to communicate between two specific objects.

  3. 紧耦合不适用 ,容易造成循环引用?

Blocks

  1. 潜在隐患:

    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
    3
    self.myTableView.selectionHandler = ^void(NSIndexPath *selectedIndexPath) {
    // handle selection ...
    };

    而 如下就不会,原因是operation 执行完后会立即释放

1
2
3
4
5
6
self.queue = [[NSOperationQueue alloc] init];
MyOperation *operation = [[MyOperation alloc] init];
operation.completionBlock = ^{
[self finishedOperation];
};
[self.queue addOperation:operation];

Target-Action

  1. Target-Action is the typical pattern used to send messages in response to user-interface events.
  2. A limitation of target-action-based communication is that the messages sent cannot carry any custom payloads.
  3. 非常松耦合,target 和 action 不用知道对方的存在,甚至target=nil ,Action 会沿着响应链一直传递直到找到响应者。On iOS, each control can even be associated with multiple target-action pairs.

参考资料

原文链接