OC-观察者练习练习
来源:互联网 发布:没权限开通淘宝联盟 编辑:程序博客网 时间:2024/05/20 03:44
main.h //被观察的对象 Jones *joens = [[Jones alloc] initWithJones]; //观察的对象 Lucy *lucy = [[Lucy alloc] initWithLucy:joens]; [[NSRunLoop currentRunLoop] run];@interface Jones : NSObject@property(nonatomic,assign) int happy;-(instancetype)initWithJones;//高兴值增加-(void)happyIncrement;————————————————————————————————@implementation Jones//高兴值-(void)happyIncrement{ //通过KVC才能触发KVO NSNumber *number = [NSNumber numberWithInt:++_happy]; //[self setHappy:++_happy]; [self setValue:number forKey:@"happy"]; //[self setHappy:12] NSLog(@"%d",self->_happy);};-(instancetype)initWithJones{ if(self = [super init]) { [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(happyIncrement) userInfo:nil repeats:YES]; } return self;}@implementation Jones//高兴值-(void)happyIncrement{ //通过KVC才能触发KVO NSNumber *number = [NSNumber numberWithInt:++_happy]; //[self setHappy:++_happy]; [self setValue:number forKey:@"happy"]; //[self setHappy:12] NSLog(@"%d",self->_happy);};-(instancetype)initWithJones{ if(self = [super init]) { [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(happyIncrement) userInfo:nil repeats:YES]; } return self;}@implementation Lucy-(instancetype)initWithLucy:(Jones *)jones{ if (self = [super init]) { //当Jones传入进来 我们就对他观察 self->_jones = jones; self->_jones.happy = 0; //添加观察者模式 /* 参数介绍 1,观察那个对象 2,观察那个属性 3,新值,和旧值 4,可以随便给 */ [_jones addObserver:self forKeyPath:@"happy" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil]; }; return self;}//如果被观察者的对象属性被改变这个对象就回被触发!-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ /** 1.参数介绍 1.keyPath 那个属性 2.object 那个对象 3.change 属性大全 **/ //如果被监听属性加到10了 移除被观察的对象 if ([[change objectForKey:@"new"] intValue] == 10) { //移除观察者对象 [_jones removeObserver:self forKeyPath:@"happy"]; } //否则打赢属性 NSLog(@"观察者调用了->%@",[change objectForKey:@"new"]); };
0 0
- OC-观察者练习练习
- oc小练习
- OC类的练习
- OC--字典练习(省市区)
- OC NSDictionary 省市区 练习
- OC语言 创建练习
- OC经典练习
- OC 练习-通讯录
- OC 数据类型 练习
- [oc实战练习三]本地推送练习
- 设计模式:观察者模式【练习】
- OC简单知识的练习
- OC字典练习 -- 中国省市区
- OC一些字符串的练习
- OC-类的创建练习
- 练习
- “++”“--”练习
- 练习
- Windows7+BluetoothSDK如何配置
- hdu 1241 dfs
- MD5算法使用简述
- js小计
- 黑马程序员——【C语言】用三种方式交换两个变量的值
- OC-观察者练习练习
- Codeforces 484D. Kindergarten DP贪心
- 软件测试工具
- 活动选择问题的动归和贪心解法
- 欢迎使用CSDN-markdown编辑器
- BPA文件解析及保存
- win7 64位机下的dsp builder 13.1及matlab安装
- 2013.03.10 组管理+基本权限管理+vim
- 【jQuery】IE与Chrome的textarea取数处理