objective-c KVO (key value observe)

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值