iOS开发 --- KVO

给苹果文档稍微翻译下:

      Key-value observing is a mechanism that enables an object to be notified directly when a property of another object changes. Key-value observing (or KVO) can be an important factor in the cohesiveness of an application. It is a mode of communication between objects in applications designed in conformance with the Model-View-Controller design pattern. 

  KVO 是一种可以让一个对象可以监听到另一个对象属性变化的机制。KVO是一个可以提高APP内聚的重要的因素。这是一个在MVC设计模式下的对象之间的通信方式。

如何使用KVO呢?在哪里可以用到KVO? 我们可以通过KVO监听tableView的contentOffset等属性来做一些事情,例如可以改变tableView导航的颜色,alpha值。

首先,对需要监听的对象添加观察者

[self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

然后实现监听属性值的回调方法

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context

{

}

最后需要在 dealloc方法中 remove掉监听者

- (void)dealloc{

[self.tableView  removeObserver:self forKeyPath:@"contentOffset" context:nil];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容