您的位置:首页 > 其它

KVO初级

2015-09-16 20:17 218 查看
ViewController.m

#import "ViewController.h"
#import "Person.h"
@interface ViewController ()

//被观察对象的生命周期够长,如果被观察对象释放,要取消观察
@property (nonatomic,strong)Person * p1;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//    观察者模式:就是判断有没有调用set方法

//    创建好被观察者
_p1 = [[Person alloc]init];

//    添加观察者
[_p1 addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];

//    改变名字
//    p1.name = @"贝爷";

}
- (IBAction)buttonAction:(id)sender {

self.p1.name = @"beiye";
}

//添加完观察者要加这个方法
//这个方法继承于NSObject
//(意味着所有的类都能作为观察者),但是一般使用Controller作为观察者

//一旦被观察者的属性发送改变,就调用这个方法
//谁观察,就必须在类里写这个方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

self.view.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];

NSLog(@"keyPath : %@",keyPath);
NSLog(@"object : %@",object);
NSLog(@"Change : %@",change);
NSLog(@"context : %@",context);

}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end


Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic,copy)NSString * name;
@property (nonatomic,assign)NSInteger * age;

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: