【苹果开发】通过KVO解除类之间的耦合


 

 1.概述

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 观察者

全部评论

相关推荐

吴offer选手:我卡在笔试才是最好笑的,甚至没给我发过笔试链接
投递哔哩哔哩等公司7个岗位
点赞 评论 收藏
分享
Ncsbbss:又想干活又想要工资,怎么什么好事都让你占了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务