KVO的简单使用

KVO即“键值监听”,通常需要三步:

1、添加监听对象【addObserver: forKeyPath: options: context:】

2、执行监听代理【- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object{}】

3、移除监听【removeObserver: forKeyPath: context: 】

KVO_Demo


图片示例:



代码示例:

//----------在.h文件中

#import<UIKit/UIKit.h>

@interfaceViewController :UIViewController

@end

//----------在.m文件中

#import"ViewController.h"

@interface ViewController()

@property(nonatomic ,strong)NSString *price;

@end

@implementation ViewController

- (void)viewDidLoad {

[superview DidLoad];

self.price=@"10";

//添加监听对象

[self addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

NSLog(@"---------%@",_price);

[self performSelector:@selector(changeGrade) withObject:nil afterDelay:5.0];

}

- (void)changeGrade {

self.price=@"10000";

}

//执行监听代理

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

change:(NSDictionary*)change context:(void*)context

{

if(object ==self && [keyPath isEqualToString:@"price"]) {

NSLog(@"---------%@",_price);

}else{

[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

}

}

//移除监听

- (void)dealloc {

[self removeObserver:self forKeyPath:@"price" context:nil];

}

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

推荐阅读更多精彩内容