首页 > 移动平台 > 详细

kvo-观察者-iOS

时间:2014-08-17 12:58:22      阅读:261      评论:0      收藏:0      [点我收藏+]
#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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!