
上QQ阅读APP看书,第一时间看更新
5.5 KVO
在如今比较流行的MVVM设计模式中,需要有一种双向绑定的机制,在数据模型发生了修改之后,立即将改变呈现到视图View上去。iOS开发过程中,基于KVO(Key Value Observing)即可实现这种模型和视图的联动机制。
KVO其实是一种观察者模式,利用它可以很容易实现视图View和数据模型的分离。当数据模型的属性值改变之后,作为监听器的视图组件就会触发特定的方法,在该方法中可以获取数据模型变更的数值,从而更新界面UI。
1.KVO中常用的方法
使用KVO的话下方的方法是比较常用的。
- 模型对象注册指定KeyPath的监听方法。通常情况下,当模型对象的指定Key发生变化时,通知视图对象。

- 视图对象的监听回调方法,在该方法中可以获取数据模型变化前后的数据。

- 删除指定Key路径的监听器。

2.使用KVO实现模型与视图联动的步骤
当需要使用KVO实现模型与视图的联动操作时,可以使用如下步骤进行:
- 创建数据模型对象,并且注册需要监听的KeyPath。
- 在视图类中,实现监听回调方法,即当收到模型对象指定KeyPath发生变化时,对界面UI执行的更新操作。
3.示例代码
下面的案例中,创建了一个模型类和一个自定义视图类,当模型类的数值发生变化时,会实时反映到界面UI中。
- 创建一个Single View Application工程。
- 定义Person模型类,并添加一个name属性。

- 定义MYLabel视图类,继承自UILabel,在MYLabel.h中添加一个Person类型的属性,该属性为MYLabel提供展示的数据。

- 在MYlabel.m文件中,重写viewData属性的setter方法,当设置viewData属性时,更新MYLabel上的文字显示。

- 在MYLabel.m文件中,实现视图对象的监听回调方法,该方法在模型数据发生变化时会调用,此时会把数据模型中最新的数据从change参数中获取,等获取到最新的数据后,更新MYLabel的文字显示。

- 在ViewController.m文件中,添加Person类型的属性以及MYLabel类型的属性,并对myLabel属性进行懒加载操作。

- 在ViewDidLoad方法中,创建Person类对象,并注册需要监听的KeyPath。

- 单击屏幕时,更新Person类对象的值,此时会调用MYLabel类中的observeValueForKeyPath:ofObject:change:context:方法,从而更新MYLabel对象的显示。
