第14章 Using Notifications

第14章 Using Notifications
接上一章的例子,如果我们打开了多个RaiseMan的文档,在“属性”里更改了背景颜色后,如何让所有打开的文档的背景颜色都改变?本章就是通过这个功能的实现,来讲解消息机制。
每一个运行中的程序都有一个“消息中心”。如果有对象对某些消息感兴趣,它就需要在“消息中心”里注册自己。注册之后的对象叫做“observer”。如果有对象发出了这个消息,就会被observer知道。它就会执行为这个消息设定好的消息处理函数。发出消息的对象叫“poster”。
用家教打个比方。中介就是“消息中心”。各科老师就是“observer”,他们需要到中介里进行注册表示对某一门课程的教学兴趣。当某个学生(poster)发出了“我想要学习数学”的消息时。数学老师就会知道这个学生,就会开始教导这个学生学习数学的课程。

在本章的例子中,每个document都注册为observer,它们都对“改变颜色(BNRColorChangedNotification)”的消息感兴趣。当用户在“属性”对话框里改变颜色之后,发出“改变颜色”的消息。此时,每个document都会知道颜色改变这件事。会
执行注册时定义好的函数(handleColorChange:  ),来进行处理。

1.注册为observer

- (id)init
{
if (![super init])
return nil;

employees = [[NSMutableArray alloc] init];

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(handleColorChange: )
name:BNRColorChangedNotification
object:nil];
NSLog(@"Registered with notification center");
return self;
}

2.发送消息

- (IBAction)changeBackgroundColor: (id)sender
{
NSColor *color = [colorWell color];
NSData *colorAsData =
[NSKeyedArchiver archivedDataWithRootObject:color];
[[NSUserDefaults standardUserDefaults] setObject:colorAsData
forKey:BNRTableBgColorKey];

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
NSLog(@"Sending notification");
[nc postNotificationName:BNRColorChangedNotification object:self];
}

3.处理消息函数

- (void)handleColorChange: (NSNotification *)note
{
NSLog(@"Received notification: %@", note);
}

4.在不关注消息时,在“消息中心”里去除observer。

- (void)dealloc
{
[self setEmployees:nil];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self];
[super dealloc];
}

当设置了delegate之后,标准的cocoa object已经为一些消息自动注册了。例如当发出NSWindowDidResizeNotification消息时,就可以调用- (void)windowDidResize: (NSNotification *)aNotification 函数进行处理。它们的命名规范都是固定的,即去除消息头的“NS”和尾部的“Notification”,剩下的部分就是消息处理函数了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值