IOS KVO与NSNotificationCenter简单使用

每次面试都被问到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

posted @ 2015-11-19 12:01  菱子  阅读(570)  评论(0编辑  收藏  举报