iOS学习笔记69-再细读KVO
2016-04-22 18:42
309 查看
[罗国强原创]
KVO - Key-Value Observing. 它提供了一种机制,允许对象被通知到其他对象的具体特性的变化。它特别适用于一个应用的模型层与控制层的交互。
一种典型的应用场景是在一个视图控制器里面,一个视图观察一个模型对象的属性。一个模型对象可以观察其它模型对象甚至它自己。
KVO也分2种,一种是自动的KVO,一种是手动的KVO。
NSObject自动支持KVO特性并且默认情况下一个类的属性支持kvc都可以使用。如果你遵循标准的Cocoa编码和命名规则,你可以使用自动更改通知你不需要写任何额外的代码。手动更改通知提供额外的控制时发出的通知,并要求额外的编码。你可以通过类的方法automaticallynotifiesobserversforkey:控制您的类属性自动通知。
自动模式的KVO
NSObject提供了基本的自动键-值改变通知。
手动模式的KVO
实现手动通知的对象必须实现
在我们注册键-值的时候,有2种情况:
1)1对1关系
To trigger notifications automatically for a to-one relationship you should either override
implement a suitable method that follows the pattern it defines for registering dependent keys.
2)1对多关系
The
to a Employee, and Employee has a salary attribute. You might want the Department object have a
this with, for example,
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
totalSalaryattribute that is dependent upon the salaries of all the Employees in the relationship. You can not do
this with, for example,
keyPathsForValuesAffectingTotalSalaryand returning
employees.salaryas a key.
相关文章推荐
- ios设备进行弱网测试的方法
- 制作一个属于自己的CocoaPods文件!
- ios 富文本
- iOS5新特性: Core Image 示例
- iOS- 自定义导航控制器(-)
- iOS textfield属性详解
- iOS,推送通知
- iOS 更改项目名称
- iOS中数据持久化,数据转化问题。
- iOS --KVO
- IOS合并lib(.a)库的终极可用方法(可用于解决duplicate symbol静态库冲突)
- iOS 原生态分享功能的实现
- iOS开发,使用友盟快速分享与第三方的白名单
- iOS 运行时
- IOS中tableviewcell.frame.size返回的是cell在storyboard中的尺寸
- IOS中tableviewcell.frame.size返回的是cell在storyboard中的尺寸
- [iOS] XCode实用快捷键
- iOS到Mac OS之自定义Label
- iOS 应用安全攻防(六):Clutch
- iOS 自定义控件--纯代码或者xib&storyBoard 系统会调用的方法