首页 > 代码库 > KVO监听

KVO监听

Main.m

#import "Children.h"
#import "Nurse.h"


int main(int argc, const char * argv[])
{
    
    Children *children = [[Children alloc] init];
    
    Nurse *nurse = [[Nurse alloc] initWithChildren:children];
    
    [[NSRunLoop currentRunLoop] run];
    
    [children release];
    [nurse release];
    
    return 0;
}

Children.h

@interface Children : NSObject {

    NSInteger _happyValue;
    
}

@property (nonatomic, assign) NSInteger happyValue; //欢乐值
@property (nonatomic, assign) NSInteger hungryValue;    //饥饿值

Children.m

@implementation Children

- (id)init {

    self = [super init];
    
    if (self) {
        //开启定时器
        [NSTimer scheduledTimerWithTimeInterval:1
                                         target:self
                                       selector:@selector(timeAction:)
                                       userInfo:nil
                                        repeats:YES];
        _happyValue = http://www.mamicode.com/100;>
Nurse.h

@class Children;

@interface Nurse : NSObject {

    Children *_chiledren;
    
}

- (id)initWithChildren:(Children *)children;

Nurse.m

#import "Children.h"

@implementation Nurse

- (id)initWithChildren:(Children *)children {

    self = [super init];
    
    if (self) {
        _chiledren = [children retain];
        
        //使用KVO监听小孩的属性happyValue变化
        [_chiledren addObserver:self
                     forKeyPath:@"happyValue"
                        options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                        context:NULL];
        
        //使用KVO监听小孩的属性hungryValue变化
        [_chiledren addObserver:self
                     forKeyPath:@"hungryValue"
                        options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                        context:NULL];
    }
    
    return self;
}

//小孩属性变化的时候,接收事件的方法
- (void)observeValueForKeyPath:(NSString *)keyPath  //观察的对象的属性名
                      ofObject:(id)object   //观察的对象
                        change:(NSDictionary *)change
                       context:(void *)context {

//    NSLog(@"change:%@",change);
    
    NSNumber *newNum = [change objectForKey:@"new"];
    int value = http://www.mamicode.com/[newNum intValue];>

KVO监听