ios

[罗国强原创]

KVO - Key-Value Observing. 它提供了一种机制,允许对象被通知到其他对象的具体特性的变化。它特别适用于一个应用的模型层与控制层的交互。

一种典型的应用场景是在一个视图控制器里面,一个视图观察一个模型对象的属性。一个模型对象可以观察其它模型对象甚至它自己。

KVO也分2种,一种是自动的KVO,一种是手动的KVO。

NSObject自动支持KVO特性并且默认情况下一个类的属性支持kvc都可以使用。如果你遵循标准的Cocoa编码和命名规则可以使用自动更改通知你不需要写任何额外的代码。手动更改通知提供额外的控制发出的通知并要求额外的编码你可以通过类的方法automaticallynotifiesobserversforkey:控制您的属性自动通知

自动模式的KVO

NSObject提供了基本的自动键-值改变通知。

手动模式的KVO

实现手动通知的对象必须实现 automaticallyNotifiesObserversForKey 方法。为了实现手动观察消息,你必须在改变值之前调用 willChangeValueForKey: ,改变值之后调用 didChangeValueForKey:

在我们注册键-值的时候,有2种情况:

1)1对1关系

To trigger notifications automatically for a to-one relationship you should either override keyPathsForValuesAffectingValueForKey: or implement a suitable method that follows the pattern it defines for registering dependent keys.

2)1对多关系

The keyPathsForValuesAffectingValueForKey: method does not support key-paths that include a to-many relationship. For example, suppose you have a Department object with a to-many relationship (employees) to a Employee, and Employee has a salary attribute. You might want the Department object have a totalSalary attribute that is dependent upon the salaries of all the Employees in the relationship. You can not do this with, for example, keyPathsForValuesAffectingTotalSalary and returning employees.salary as a key.

原文地址:https://www.cnblogs.com/luoguoqiang1985/p/3608261.html