kvo-观察者-iOS

#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,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。