add observer的两个用法

作者:Love@YR
链接:http://blog.csdn.net/jingqiu880905/article/details/50524016
请尊重原创,谢谢!

addObserver有两种时候会调

一种是广播

发广播的方法:

[[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATIONNAME object:nil userInfo:userinfo];//userinfo是个dictionary

监听广播:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectorName:) name:NOTIFICATIONNAME object:nil];
//收到广播要做的事件
-(void)selectorName:(NSNotification *)notification{
    NSDictionary *dic= [notification userInfo];
}

第二种是KVO

    per= [[Person alloc] init];  //per是全局的
    [per setValue:@"annie" forKey:@"name"];  
    [per setValue:@"20" forKey:@"age"];      
    [per addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    //此处的self是谁来监听per的变化,谁来监听在谁那里调回调方法

添加默认的响应回调方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context  
{  //object为per ,keyPath为age
    if([keyPath isEqualToString:@"age"])  
    {  
    //do something
    }  
}  

监听释放

- (void)dealloc  
{   
    [per removeObserver:self forKeyPath:@"age"]; //kvo的
    [NSNotificationCenter defaultCenter]removeObserver:self]; //广播的
    [per release]; 
    //[super dealloc];  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值