KVO:当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
使用步骤大体概括为3步:
1. 注册,指定被观察者的属性
2. 实现回调方法
3. 移除观察
下面附上一段简单代码来明确下kvo的使用:
首先说明下大体代码含义:声明一可变字典,开始时给字典中键值为hello的做一个value的赋值,并通过kvo对此键值做观察,当点击了一个button后,对这个hello的key所对应的value做出相应的改变,此时也会触发kvo的方法。。
#import "LoginViewController.h"
@interface LoginViewController ()
@property (nonatomic, strong)NSMutableDictionary *dictiony;
@end
@implementation ZKLoginViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(, , , )];
[button setTitle:@"测试kvo" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
_dictiony = [NSMutableDictionary dictionary];
[_dictiony setValue:@"10.0" forKey:@"hello"];
[_dictiony addObserver:self forKeyPath:@"hello" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
}
//一点击按钮让字典中对应的键的value发生改变,这时由于kvo,会触发观察者的方法
-(void)buttonClicked:(UIButton *)button {
[_dictiony setValue:@"11.0" forKey:@"hello"];
}
//触发的方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSLog(@"触发了kvo方法");
}