#import <Foundation/Foundation.h>
#import "Banker.h"
@interface Users : NSObject{
Banker *bankAccount;
}
- (void)registerAsObserver;
@end
#import "Users.h"
@implementation Users
- (id)init
{
self = [super init];
if (self){
bankAccount = [[Banker alloc]init];
}
return self;
}
static void *OpeningBalance = (void *)&OpeningBalance;//定义一个指针型的对象地址,区分相同key的不同context
- (void)registerAsObserver
{
//添加一个obsever 新旧zhi都传递过去
[bankAccount addObserver:self forKeyPath:@"openingBalance" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:OpeningBalance];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//object参数,表示Banker的对象
NSLog(@"old...%@", [change objectForKey:NSKeyValueChangeOldKey]);
if (context == OpeningBalance){
NSString *value = [change objectForKey:NSKeyValueChangeNewKey];
NSLog(@"new %@", value);
}
}
@end
#import <Foundation/Foundation.h>
@interface Banker : NSObject{
float openingBalance;
}
@property (assign) float openingBalance;
@end
#import "Banker.h"
@implementation Banker
@synthesize openingBalance = _openingBalance;
- (id)init
{
self = [super init];
if (self){
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(balanceUpdate:) userInfo:nil repeats:YES];
}
return self;
}
- (void)balanceUpdate:(id)arg
{
float f = self.openingBalance;
f += arc4random() % 100;
self.openingBalance = f;
}
@end
objective-c KVO (key value observe)
最新推荐文章于 2021-12-10 20:04:14 发布