NSNotification
提到通知,我们先来简单地走一下流程:
对象A在通知中心NotificationCenter注册了一个观察者Observer,注册时指定了它将要观察的通知是谁(NotificationName)、发送通知的对象(object参数,如果为nil,即所有对象都可以)。NotificationCenter会维护一张注册表,每一条记录可以查看注册者、通知名等信息。对象B负责向NotificationCenter发送通知(post),NotificationCenter接收到通知后,根据通知名在注册表中查询有些注册者关注了该通知,然后像符合条件的注册者广播通知,这里当然是向对象A 发送通知了,对象A在侦听到通知后会回调它注册时指定的一个方法。至此,通知流程结束,移除观察者;值得注意的是,对象A和对象B一般来自不同类,通知更多地使用于完全独立,联系不紧密的两个类之间的通信。
下面用代码来实现上面的流程:
(1)不传参
1、对象A注册观察者:
[[NSNotificationCenterdefaultCenter]addObserver:self selector:@selector(update:)name:@"UPDATEUINOTIFICATION" object:nil];
2、 对象B发送通知:
[[NSNotificationCenterdefaultCenter]postNotificationName:@"UPDATEUINOTIFICATION" object:self];
[[NSNotificationCenterdefaultCenter]removeObserver:self];
接下来我们来看看NSNotification的内部:
@interfaceNSNotification : NSObject<NSCopying, NSCoding>
@property (readonly, copy) NSString *name;
@property (readonly, retain) id object;
@property (readonly, copy) NSDictionary *userInfo;
@end
可以看到它有三个属性:name指定通知名,object指定侦听哪些对象,userInfo一般用于传参,在回调方法中可以通过[notifationuserInfo]来获得字典,从而得到其中的参数。
注册时如果name为空,object非空,那么观察者将侦听该object对象发出的所有通知;
注册时如果name非空,object为空,那么观察者将侦听这个指定通知,而不管该通知是哪一个对象发出;
(2)传参
1、对象A注册观察者:
[[NSNotificationCenterdefaultCenter]addObserver:self selector:@selector(update:)name:@"UPDATEUINOTIFICATION" object:nil];
2、对象B发送通知:
NSDictionary *dic =[NSDictionarydictionaryWithObject:valueforKey:@"value"];
[[NSNotificationCenterdefaultCenter]postNotificationName:@"UPDATEUINOTIFICATION"object:selfuserInfo:dic];
3、回调方法:
-(void)update:(NSNotification *)notification {
[[notificationuserInfo]valueForKey:@"value"];
}
4、移除观察者:
[[NSNotificationCenterdefaultCenter]removeObserver:self];