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;
}