首页 > 移动平台 > 详细

IOS KVO与NSNotificationCenter简单使用

时间:2015-11-19 13:09:37      阅读:338      评论:0      收藏:0      [点我收藏+]

每次面试都被问到KVO或者通知。今天也自己来看了看通知。

1、NSNotificationCenter使用。

使用步骤:添加观察者、发送通知、移除观察者。

添加观察者:哪里需要接收通知,就在哪里加。例如:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reciveNotfi:) name:@"testNot" object:nil];

 发送通知:

[[NSNotificationCenter defaultCenter]postNotificationName:@"testNot" object:nil userInfo:@{@"value":dTF.text}];

接收数据在reciveNotfi处理。

-(void)reciveNotfi:(NSNotification *)sender{

    NSDictionary *userInfo=sender.userInfo;

    otherLabel.text=[userInfo objectForKey:@"value"];

}

移除观察者:

 [[NSNotificationCenter defaultCenter]removeObserver:self name:@"testNot" object:nil];

注:name必须一致

参考链接:http://my.oschina.net/u/2340880/blog/406163

2 KVO

KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

注:一定要是属性,私有变量是不可以的。属性赋值时不能用例如:_count=1;要用self.count=1;否则不生效。

使用步骤:添加观察者,数据处理,移除观察者

添加观察者:

[self addObserver:self forKeyPath:@"count" options:NSKeyValueObservingOptionNew context:nil];

注:被观察的对象的属性

数据处理:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

    if ([keyPath isEqualToString:@"count"]) {

    //todo

    }

}

移除观察者:

[self removeObserver:self forKeyPath:@"count"];

另外附上demo:https://github.com/LingZi123/KVOAndNSNotificationCenter.git

IOS KVO与NSNotificationCenter简单使用

原文:http://www.cnblogs.com/luojiao-lx/p/4977187.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!