码迷,mamicode.com
首页 > 移动开发 > 详细

kvo-观察者-iOS

时间:2014-08-17 12:58:22      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:blog   os   io   for   ar   cti   div   log   

#import <Foundation/Foundation.h>

@interface Child : NSObject
@property (nonatomic,assign) int age;
-(id) initWithAge:(int) age;
@end

 

#import "Child.h"

@implementation Child
-(id) initWithAge:(int) age{
    self=[super init];
    if(self!=nil){
        _age=age;
    }
    return self;
}
@end

 

#import <Foundation/Foundation.h>
@class Child;
@interface Nurse : NSObject
@property Child *child;
-(id)initWithChild:(Child *) child;
-(void) observeChild;
-(void) removeObserver;
@end

 

#import "Nurse.h"
#import "Child.h"


@implementation Nurse
#import "Child.h"
-(id)initWithChild:(Child *) child{
    self=[super init];
    if(self!=nil){
        _child=child;
//         [_child addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"孩子长大一岁了"];
    }
    return self;
}

-(void) observeChild{
    [_child addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
        NSLog(@"观察者创建好了");
}

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@"孩子现在的年龄:%@",[change objectForKey:@"new"]);
}

-(void) removeObserver{
[_child removeObserver:self forKeyPath:@"age"];
     NSLog(@"观察者移除掉了");
}

@end

 

    //kvo--观察者
        Child *child=[[Child alloc] initWithAge:23];
        Nurse *nurse=[[Nurse alloc] initWithChild:child];
        [nurse observeChild];
        [child setAge:24];
        [child setAge:25];
        [nurse removeObserver];

 

kvo-观察者-iOS,布布扣,bubuko.com

kvo-观察者-iOS

标签:blog   os   io   for   ar   cti   div   log   

原文地址:http://www.cnblogs.com/clarence/p/3917632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!