kvo-观察者-iOS

时间:2024-10-04 22:03:20
#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];