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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容