KVO 和 NSNotification

来源:互联网 发布:淘宝客api教程 编辑:程序博客网 时间:2024/06/05 14:31
自己根据网上的列子又加上自己的一些补充

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
这个观察者在监听到anObject发送名字为aName的notification时,调用selector的方法,在aSelector方法中得到userInfo。
anObject表示从谁那儿发送出来的消息
例如注册了三个name为66的观察者,
@1
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(next:) name:@"66" object:@"99"];
@2
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(print) name:@"66" object:@"77"];
@3
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(print1) name:@"66" object:nil];
通知者发消息
[[NSNotificationCenter defaultCenter] postNotificationName:@"66" object:@"99"];

通知者99向name为66的观察者发消息,@1只接受name为66,对象99的消息, @2只接受name为66,对象77的消息,@3接受只要是name为66的任何对象的消息,所以,@1和@3会受到通知者的消息分别会调用selector的方法

比如:
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(onWebClose)name:@"WebClose"object:nil];
也就是说监听到了object:nil发出消息,消息的名字是WebClose,此时observer就调用onWebClose方法。
如果object:nil表示以广播方式发消息或者得到消息,这个时候只要消息名字是对的就可以得到这个消息。
object 是用于过滤Notication的,只接收指定Sender所发的Notification
然后在被监听的类中发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"WebClose"object:nil];
这样观察者就接到了消息会调用selector方法;
最后记得移除这个观察者:
[[NSNotificationCenter defaultCenter] removeObject:self];

KVO

监听对象
[_p addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionOld context:nil];
//当监控的某个对象的属性发生改变时调用
keyPath:对象的哪个属性发生了变化
object:哪个对象的属性发生了变化
change:属性的修改情况(属性原来的值,属性最新的值), 与上面options中传值对应,如果按照上面的,现在字典里只有老的值。
context:上面传递过来的值
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString*, id>*)change context:(void *)context
{

}

最后不要忘了移除这个观察者
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"age"];
}
---------


0 0
原创粉丝点击