首页 > 代码库 > kvo-观察者-iOS
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];
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。