通知机制和KVO都是通过—------观察者模式实现的
KVO,
即:
Key-Value Observing
,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
前者是:被观察对象直接向观察者发送通知
后者是:一个中心对象为所有观察者提供变更通知
参数解释:
defaultCenter,消息中心只有一个,通过类方法获取它的单例。
addObserver,添加监听者实例,此处为当前实例
selector,observer中的一个方法指针,当有消息的时候会执行此方法,并把相关上下文以参数传递过去
name,注册所关心消息的名称,
object,这个是对消息发送方的一个过滤,此参数据说明当前监听器仅对某个对象发出的消息感兴趣。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationMethod:) name:UIApplicationDidEnterBackgroundNotification object:@"大大”]; //相同NotificationName只接受object:@“大大”的发送者的接收,如果object = nil,相同NotificationName都接收
[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:@"大大" userInfo:@{@"name":@"1111"}];
[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:@"大大111" userInfo:@{@"name":@"2222"}];
通过实现:
//
注册观察者
[[NSNotificationCenter
defaultCenter] addObserver:self selector:@selector(handleMessage:) name:kDZTestNotificatonMessage object:nil];
//被观察者----->发送通知给观察者
[[NSNotificationCenter
defaultCenter] postNotificationName:kDZTestNotificatonMessage object:Nil userInfo:@{}];
- (void)alipayReturn:(NSNotification *)result {
NSLog(@"112");
NSDictionary * resultDic = result.object;
}
//退出要移除观察对象,不然耗内存(每时每刻等待通知接收,好性能)
-(void)
dealloc
{
[[NSNotificationCenter
defaultCenter] removeObserver:self];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)