每个运行中的application都有一个NSNotificationCenter的成员变量,它的功能就类似公共栏. 对象注册关注某个确定的notification(如果有人捡到一只小狗,就去告诉我). 我们把这些注册对象叫做 observer. 其它的一些对象会给center发送notifications(我捡到了一只小狗). center将该notifications转发给所有注册对该notification感兴趣的对象. 我们把这些发送notification的对象叫做 poster
很多的标准Cocoa类会发送notifications: 在改变size的时候,Window会发送notification; 选择table view中的一行时,table view会发送notification;我们可以在在线帮助文档中查看到标准cocoa对象发送的notification
-- NSNotification 和 NSNotificationCenter
Notification对象非常简单. 它就是poster要提供给observer的信息包裹. notification对象有两个重要的成员变量: name 和 object. 一般object都是指向poster(为了让observer在接受到notification时可以回调到poster)
所以,notification有两个方法
- (NSString *)name
- (id)object
NSNotificaitonCernter是架构的大脑了.它允许我们注册observer对象, 发送notification, 撤销observer对象注册
下面是它的一些常用方法
+ (NSNotificationCenter *)defaultCenter
返回notification center [类方法,返回全局对象, 单件模式.cocoa的很多的全局对象都是通过类似方法实现]
- (void)addObserver:(id)anObserver
selector:(SEL)aSelector
name:(NSString *)notificationName
object:(id)anObject
注册anObserver对象:接受名字为notificationName, 发送者为anObject的notification. 当anObject发送名字为notificationName的notification时, 将会调用anObserver的aSelector方法,参数为该notification
如果notificationName为nil. 那么notification center将anObject发送的所有notification转发给observer
. 如果anObject为nil.那么notification center将所有名字为notificationName的notification转发给observer
- (void)postNotification:(NSNotification *)notification
发送notification至notification center
- (void)postNotificationName:(NSString *)aName
object:(id)anObject
创建并发送一个notification
- (void)removeObserver:(id)observer
移除observer
例子:
在 @implementation testController 里
UIButton* footerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
footerButton.frame = CGRectMake(0, 0, 100, 30);
footerButton.center = CGPointMake(160, 20);
footerButton.titleLabel.textAlignment = UITextAlignmentCenter;
footerButton.backgroundColor = [UIColor clearColor];
[footerButton setTitle:@"123" forState:UIControlStateNormal];
//[footerButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//[footerButton setBackgroundImage:[[UIImage imageNamed:@"ni.jpg"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0] forState:UIControlStateNormal];
[footerButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:footerButton];
//注册监听对象
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(handNotification:) name:@"hand" object:footerButton];
//在button按下事件回调中post通知
-(void)buttonAction:(id)sender
{
UIButton* button = (UIButton*)sender;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"hand" object:button];
}
//在通知的回调实现
-(void)handNotification:(NSNotification*)note
{
UIButton *botten = (UIButton*)note.object;
if([botten.titleLabel.text length] < 5)
{
[botten setTitle:@"nsnotification" forState:UIControlStateNormal];
[[NSNotificationCenter defaultCenter] removeObserver:self];//移除
}
else
{
[botten setTitle:@"456" forState:UIControlStateNormal];
}
}