iOS —— 通知、监测KVO

来源:互联网 发布:linux如何查看登录情况 编辑:程序博客网 时间:2024/06/05 20:40

KVO

//初始化时,注册观察者,监听属性的变化

-(id)init
{
    if (self=[super init]) {
        [self addObserver:self forKeyPath:@"book" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
    return self;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"name"])
{
//打印旧值,新值
NSLog(@"changed:old->%@;new->%@",[change objectForKey:@"old"],[change objectForKey:@"new"]);
}
}
//最后,重写dealloc方法,移除监听
-(void)dealloc
{
    [self removeObserver:self forKeyPath:@"name"];
    [super dealloc];
}

NOtification
//注册通知中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(print) name:@"name" object:nil];
//发送通知,注册中心就会调用方法print

[[NSNotificationCenter defaultCenter] postNotificationName:@"name" object:nil userInfo:nil];




0 0
原创粉丝点击