KVO 是监听键值。只要对象被监听的属性发生变化,那么就会执行监听方法(回调方法)
//
// ViewController.m
// KVO
//
// Created by hhg on 15/9/28.
// Copyright (c) 2015年 hhg. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () {
UILabel *label;
}
@property (nonatomic ,strong) Person *john;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 100, 30);
button.backgroundColor = [UIColor greenColor];
[self.view addSubview:button];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
label = [[UILabel alloc]initWithFrame:CGRectMake(100, 170, 100, 30)];
[self.view addSubview:label];
//创建数据对象
self.john = [[Person alloc]init];
[self.john setValue:@"hello" forKey:@"name"];
//设定监听属性
[self.john addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
[self.john addObserver:self forKeyPath:@"age" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
}
//监听方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSLog(@"%@",keyPath);
label.text = [NSString stringWithFormat:@"%03d",arc4random()%10000];
NSLog(@"change = %@",change);
}
-(void)buttonClick:(UIButton *)butt {
unsigned int k = arc4random()%100;
[self.john setValue:[NSNumber numberWithUnsignedInt:k] forKey:@"age"];
[self.john setValue:@"hi" forKey:@"name"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
person类只有两个属性
//
// Person.h
// KVO
//
// Created by hhg on 15/9/28.
// Copyright (c) 2015年 hhg. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject {
NSUInteger age;
}
@property (nonatomic,assign) NSString *name;
@end