涉及3个方法:
1.为对象的某个属性添加观察者
例如为lable的text属性添加观察者,self表示控制器是lable的text属性的观察者
[lable addObserver:self forKeyPath:@"text" options:0 context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{//当lable的text属性被修改了之后,你想干什么,就写在这里
}
3.当对象被销毁时,移除观察者(如果不移除,可能因为对象已经不在了,但通知还在,导致崩溃)
- (void)dealloc
{
[self.myLable removeObserver:self forKeyPath:@"text"];
}
源代码如下,拷贝后即可运行:
//
// ViewController.m
// KVOLearn
//
// Created by wusiping on 15/11/30.
// Copyright (c) 2015年 wusiping. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic, weak)UIButton *btn;
@property(nonatomic, weak)UILabel *myLable;
@property(nonatomic, weak)UILabel *myLable2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self addBtn];
[self addLable];
[self addLable2];
}
//添加一个按钮,来改变lable的属性
- (void)addBtn
{
CGFloat btnX = 200;
CGFloat btnY = 200;
CGFloat btnW = 100;
CGFloat btnH = 50;
CGRect btnFrame = CGRectMake(btnX, btnY, btnW, btnH);
UIButton *btn = [[UIButton alloc]initWithFrame:btnFrame];
btn.backgroundColor = [UIColor redColor];
[btn setTitle:@"数字加一" forState:UIControlStateNormal];
_btn = btn;
[_btn addTarget:self action:@selector(touchBtn:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_btn];
}
//点击按钮时,触发的操作
- (void)touchBtn:(UIButton *)btn
{
static int i = 0 ;
_myLable.text = [NSString stringWithFormat:@"哈哈%d",i ];
i ++;
}
//用于展示lable1
- (void)addLable
{
CGFloat lableX = 50;
CGFloat lableY = 50;
CGFloat lableW = 100;
CGFloat lableH = 50;
CGRect lableFrame = CGRectMake(lableX, lableY, lableW, lableH);
UILabel *lable = [[UILabel alloc]initWithFrame:lableFrame];
lable.text = @"hello";
//添加观察者
[lable addObserver:self forKeyPath:@"text" options:0 context:nil];
_myLable = lable;
[self.view addSubview:_myLable];
}
//取消观察者
- (void)dealloc
{
[self.myLable removeObserver:self forKeyPath:@"text"];
}
//lable显示labe1的变化
- (void)addLable2
{
CGFloat lable2X = 50;
CGFloat lable2Y = 150;
CGFloat lable2W = 300;
CGFloat lable2H = 50;
CGRect lable2Frame = CGRectMake(lable2X, lable2Y, lable2W, lable2H);
UILabel *lable2 = [[UILabel alloc]initWithFrame:lable2Frame];
_myLable2 = lable2;
[self.view addSubview:_myLable2];
}
//当labe1的text属性被修改时,就会回调下面这个方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"mylable属性被修改为%@",_myLable.text);
_myLable2.text = [NSString stringWithFormat:@"lable1的属性被修改为%@",_myLable.text];
}
@end