KVO初级
2015-09-16 20:17
218 查看
ViewController.m
Person.h
#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
相关文章推荐
- Android多媒体之调用摄像头和从本地相册中选择图片
- 平方和
- UI_模态跳转
- POJ - 3069 Saruman's Army(贪心)
- hdu 1495 非常可乐
- SDWebImage框架清除内存中的缓存图片
- 背包DP的标准代码模板
- Oracle建立表空间、建立用户、用户授权、指定表空间、激活用户、删除用户、删除表空间
- HDU 2037 今年暑假不AC
- UIScrollView
- 网易游戏2016校园招聘“游戏研发&平台开发”在线笔试——A题 Amusing Digits
- timer.schedule定时器的使用
- Android 自定义View——自定义View控件
- H5学习之旅-H5的元素属性(3)
- 工厂模式
- VC++创建和调用dll
- vim 配置集锦
- session的生命周期
- 前端性能优化(八)
- H5学习之旅-H5的元素属性(3)