IOS KVO使用小结

Book

#import "Book.h"

@implementation Book
@synthesize price = _price;

- (id) init {
    self = [super init];
    if (self) {
        self.price = 100.0;
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    }
    return self;
}

- (void) timerAction:(NSTimer *) timer{
    self.price--;
}
@end


#import "Book.h"

@implementation Book
@synthesize price = _price;

- (id) init {
    self = [super init];
    if (self) {
        self.price = 100.0;
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    }
    return self;
}

- (void) timerAction:(NSTimer *) timer{
    self.price--;
}
@end



Person

#import <Foundation/Foundation.h>
#import "Book.h"

@interface Person : NSObject {
    Book *_book;
}

@property (nonatomic, retain) Book *book;


- (id) initWithBook:(Book *)book;
@end


#import "Person.h"

@implementation Person
@synthesize book = _book;

- (id) initWithBook:(Book *)book {
    self = [super init];
    if (self) {
        self.book = book;
        
        [self.book addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}


//监听回调
- (void) observeValueForKeyPath:(NSString *)keyPath
                       ofObject:(id)object
                         change:(NSDictionary *)change
                        context:(void *)context {
    NSLog(@"%@", change);
    
}

- (void)dealloc {
    [self.book removeObserver:self forKeyPath:@"price"];
    [super dealloc];
}
@end


使用:

#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        Book *book = [[Book alloc] init];
        
        Person *person = [[Person alloc] initWithBook:book];
        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}


日志:

2013-03-17 14:46:34.212 KVODemo[1801:303] {
    kind = 1;
    new = 99;
}
2013-03-17 14:46:35.183 KVODemo[1801:303] {
    kind = 1;
    new = 98;
}
2013-03-17 14:46:36.182 KVODemo[1801:303] {
    kind = 1;
    new = 97;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值