消息通信机制NSNotificationCenter

消息通信机制NSNotificationCenter,第1张

概述最近写程序需要用到这类,研究了下,现把成果和大家分享。 NSNotificationCenter是专门供程序中不同类间的消息通信而设置的,使用起来极为方便, 长话短说。 设置通知,就是说要在什么地方(哪个类)接受通知,一般在初始化中做。 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:) 

最近写程序需要用到这类,研究了下,现把成果和大家分享。

NSNotificationCenter是专门供程序中不同类间的消息通信而设置的,使用起来极为方便,

长话短说。

设置通知,就是说要在什么地方(哪个类)接受通知,一般在初始化中做。

[[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(test:) name:@"test" object:nil]; 

我仅对以上参数做以说明:addobserver 这个是观察者,就是说 在什么地方接收通知;

 selector 这个是收到通知后,调用何种方法;

 name: 这个是通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

发送通知,就是说此时要调用观察者处的方法。

[[NSNotificationCenter defaultCenter] postNotificationname:@"test" object:searchFrIEndarray];

我仅对以上参数做以说明:

postNotificationname:通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

object:传递的参数

发送通知时,默认调用test方法。

- (voIDtest:(NSNotification*) notification

{

searchFrIEndArrary = [notification object];//通过这个获取到传递的对象


1. 定义一个方法

-(voID) update{ }

2. 对象注册,并关连消息

[[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(update) name:
@"update" object:nil]

3. 在要发出通知消息的地方

[[NSNotificationCenter defaultCenter] postNotificationname:
:nil];

具体如何使用 Notifications

http:
//blog.sina.com.cn/s/blog_5df7dcaf0100c0q2.HTML

////////////////////////////////////////

第十四章: 使用 Notifications

用户可能使用RaiseMan并打开了几个document,然后他发现紫色的背景颜色实在是不利于阅读文档正文. 于是,他打开Preferences panel修改背景颜色,不过令人失望的是,已经存在的文档的背景颜色不会跟着改变. 于是,这个用户可能会写信给你告诉你这些. 你也许会回复:
"defualts会在document创建的时候才读取,保存document在打开实际上,用户想说明的是他希望程序能立马刷新已经打开的文档. 如果这样,那该怎么做呢?我们需要把所有打开的document用一个List记录起来么

--- 什么是Notification

这个要求其实也很容易实现. 每个运行中的application都有一个NSNotificationCenter的成员变量,它的功能就类似公共栏. 对象注册关注某个确定的notification(如果有人捡到一只小狗,就去告诉我). 我们把这些注册对象叫做 observer. 其它的一些对象会给center发送notifications(我捡到了一只小狗). center将该notifications转发给所有注册对该notification感兴趣的对象. 我们把这些发送notification的对象叫做 poster

很多的标准Cocoa类会发送notifications: 在改变size的时候,Window会发送notification; 选择table vIEw中的一行时,table vIEw会发送notification;我们可以在在线帮助文档中查看到标准cocoa对象发送的notification

在我们的例子中,我们将MyDocumet对象注册为observer. 而preference controller在用户改变color时将发送notification. Mydocument在接受到该notification后改变background color

在Mydocument对象释放前,我们必须从notification center移除我们注册的observer. 一般我们在dealloc方法中做这件事

-- Notifications 不是什么
当程序员们听到notification center的时候,他们可能会联想到IPC(进程间通讯).他们认为:
我在一个程序中创建一个observer,然后在另外一个程序中发送一个notification. 这个设计没有办法工作的,notification center允许同一个程序中的不同对象通许,它不能跨越不同的程序 [Notification 就是设计模 式中的 观察者模式,cocoa为我们实现了该模式,就像Java也有同样的实现一样]

NSNotification 和 NSNotificationCenter

Notification对象非常简单. 它就是poster要提供给observer的信息包裹. notification对象有两个重要的成员变量: name 和
. 一般object都是指向poster(为了让observer在接受到notification时可以回调到poster)

所以,notification有两个方法
(Nsstring *)name
(ID)

NSNotificaitonCernter是架构的大脑了.它允许我们注册observer对象,发送notification,撤销observer对象注册

下面是它的一些常用方法
+ (NSNotificationCenter )defaultCenter
返回notification center [类方法,返回全局对象,单件模式.cocoa的很多的全局对象都是通过类似方法实现]

)addobserver:()anObserver
selector:(SEL)aSelector
name:(Nsstring
)notificationname
:()anObject
注册anObserver对象:接受名字为notificationname,发送者为anObject的notification. 当anObject发送名字为notificationname的notification时,将会调用anObserver的aSelector方法,参数为该notification 如图14.


. 如果notificationname为nil. 那么notification center将anObject发送的所有notification转发给observer
. 如果anObject为nil.那么notification center将所有名字为notificationname的notification转发给observer

)postNotification:(NSNotification )notification
发送notification至notification center 如图14.
)postNotificationname:(Nsstring )aname
)anObject
创建并发送一个notification

)removeObserver:()observer
移除observer


发送一个Notification

发送notification是其中最简单的步骤了,所以我们从它开始实现.当我们接收到changeBackgroundcolor:消息时,PreferenceController对象发送一个notification.

我们将notification命名为
BNRcolorChanged,我们使用一个全局常量来指定.(有经验的程序员会使用一个前缀,这样避免和其他组件定义的notification混淆)打开PreferenceController.h 添加下面的的外部申明
extern Nsstring const BNRcolorChangednotification;

在PreferenceController.m中定义常量
Nsstring
BNRcolorChangednotification = ;

在PreferenceController.m修改changeBackgroundcolor:方法
(IBAction)changeBackgroundcolor:()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
:self];
}

注册成为Observer

要注册一个observer,我们必须提供几个要数: 要成为observer的对象;所感兴趣的notification的名字;当notification发送时要调用的方法. 我们也可以指定要关注莫个对象的notification.(比如说,我们需要关注莫个特定的window的resize的notification)

编辑Mydocument类的init方法
)init
{
if![super init])
return nil;

employees
[[NSMutableArray alloc] init];

NSNotificationCenter
[NSNotificationCenter defaultCenter];
[nc addobserver:self
selector:@selector(handlecolorChange:)
name:BNRcolorChangednotification
:nil];
NSLog(
Registered with notification center);
self;
}

同时在dealloc方法,将Mydocument从notification center中移除
)dealloc
{
[self setEmployees:nil];
NSNotificationCenter
[NSNotificationCenter defaultCenter];
[nc removeObserver:self];
[super dealloc];
}

处理Notification
当一个notification发生时,handlecolorChange:方法将被调用. 目前我们在方法中简单的打印一些log.
)handlecolorChange:(NSNotification )note
{
NSLog(
Received notification: %@ }
编译运行程序,看到了我们想要的log了吧


userInfo Dictionary

notification对象的object变量是poster,如果我们想要notification对象传递更多的信息,我们可以使用user info dictionary. 每个notification对象有一个变量叫 userInfo,它是一个NSDictionary对象,用来存放用户希望随着notification一起传递到observer的其它信息. Mydocument将使用它来得到要改变的color.在PreferenceController.m添加userInfo
[sender color];
NSData
colorAsData;
colorAsData
[NSKeyedArchiver archivedDataWithRootObject:color];
[[NSUserDefaults standardUserDefaults] setobject:colorAsData
forKey:BNRtableBgcolorKey];

NSNotificationCenter
);
NSDictionary
d [NSDictionary dictionaryWithObject:color
forKey:
color];
[nc postNotificationname:BNRcolorChangednotification
:self
userInfo:d];
}

在Mydocument.m,从userInfo中读取到color
NScolor [[note userInfo] objectForKey:];
[tableVIEw setBackgroundcolor:color];
}

打开几个窗口,并改变背景颜色,现在,那些打开的窗口的背景颜色立马就变了.


思考

通常当你将自己的一个对象设置为cocoa某个标准对象的delegate的时候,你同时或许也对该标准对象的notification感兴趣. 例如,我们实现一个window的delegate来处理 windowshouldClose:,我们也许会对 NSWindowDIDResiZenotification这样的notification感兴趣.

如果一个cocoa标准对象有一个delegate,同时它也发送notification的话,cocoa对象会自动将它的delegate对象注册成为observer来接受接受自己的notification. 如果我们实现了一个delegate,那么delegate[也就是我们的对象]要怎样声明来接受notification呢
[方法的名字是什么]

方法名字其实很简单: 以notification名字为基准,先将NS前缀去掉,接着将第一个字母改为小写. 在将后面的Notification去掉,然后加个冒号:. 例如,为了能接受到window的NSWindowDIDResiZenotification,delegate可以实现方法:
)windowDIDResize:(NSNotification )aNotification

当window改变大小时,这个方法将自动调用. 对于NSWindow,我们可以在.h或是帮助文档中找到类似的notification 来实现notification方法.


挑战 当程序不再是active状态是,让程序发出beep. 当unactive时,NSApplication会发送NSApplicationDIDResignActiveNotification的notificaiton. 而我们的AppController是NSApplication的delegate. 函数NSBeep()可以用来发出beep声音

总结

以上是内存溢出为你收集整理的消息通信机制NSNotificationCenter全部内容,希望文章能够帮你解决消息通信机制NSNotificationCenter所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1063471.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存