标签:
首先创建一个person类
““
@interface Person : NSObject{
BankAccount * bankAccount;
}
//打开监听银行账号的能力
- (void)registerAsObserver;
@end
““
“`
#import “Person.h”
@implementation Person
-(id)init{
self =[super init];
if(self){
bankAccount =[[BankAccount alloc]init];
}
return self;
}
//OpeningBalance 指向自己的指针
static void * openingBalance =(void *)&openingBalance;
- (void)registerAsObserver{
//监听银行账号的变化 context 后面跟一个不相同的数
[bankAccount addObserver :self forKeyPath:@"openingBalance" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:openingBalance];
/*
给银行账号bankAccount增加一个新的监听 self ,监听openingBalance的变化过程 只要openingBalance 有变化,就会调用下面的方法
*/
}
// 这个方法就是监听的回调函数
//就是说bankAccount 里面只有openingBalance有变化了,就会调用下面的这个方法
// keyPath 表示之前监听的key就是 openingBalance
// object表示bankAccount
// change是一个字典 里面包含了新,旧 的值
//context 是私有变量OpeningBalance
- (void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary
““
#import
““
#import “BankAccount.h”
@implementation BankAccount
- (id)init{
self =[super init];
if(self){
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(balanceUpdate) userInfo:nil repeats:YES];
}
return self;
}
- (void)balanceUpdate{
float f =self.openingBalance;
f +=arc4random()%100;
//切记不可以这么写 这样写会没有任何的变化
// _openingBalance=f;
//写法一
self.openingBalance=f;
//写法二
//[self setOpeningBalance:f];
//写法三 kVC 写法
//[self setValue:[NSNumber numberWithFloat:f] forKey:@"openingBalance"];
//写法四
//[self willChangeValueForKey:@"openingBalance"];
//_openingBalance=f;
//[self didChangeValueForKey:@"openingBalance"];
}
@end
““
““
#import
2016-05-10 23:32:52.415 KVO[509:11870] how
2016-05-10 23:32:53.421 KVO[509:11870] 新的值 59,旧的值0
2016-05-10 23:32:54.423 KVO[509:11870] 新的值 66,旧的值59
2016-05-10 23:32:55.421 KVO[509:11870] 新的值 130,旧的值66
更多分享请关注微博 IT一散人
标签:
原文地址:http://blog.csdn.net/maxingzehaoren/article/details/51367919