一,概述

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

一,概述KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

定义一个类A

@interface A : NSObject {

int age;

}

@end

2.定义此A为Controller的属性,实例化它,监听它的属性,并显示在当前的View里边

- (void)viewDidLoad

{

[super viewDidLoad];

a = [[A alloc] init];

a.age = 5;

[a addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];

myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];

myLabel.textColor = [UIColor redColor];

myLabel.text = [NSString StringWithFormat:@"%d",a.age];

[self.view addSubview:myLabel];

UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];

b.frame = CGRectMake(0, 0, 100, 30);

[b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:b];

}

3.当点击button的时候,调用buttonAction方法,修改对象的属性

-(void) buttonAction

{

a.age += 5;

}

4.实现回调方法

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

{

if([keyPath isEqualToString:@"age"])

{

[NSString StringWithFormat:@"%d",a.age];

}

}

5.最后当页面退出时需remove观察者

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航