NSNotification消息通信

创建消息中心

[NSNotificationCenter defaultCenter]单例模式

添加观察者

为不同的类之间提供消息通信机制。

使用NSNotificationCenter的单例创建一个消息中心:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLabelValue:) name:@"label" object:nil];

addObserver:self是添加一个观察者,即消息的接收者,不能为空;

selector:@selector(changeLabelValue:)是接收到消息后观察者执行的方法,这个方法必须且只能有一个参数(即一个NSNotification实例),如                    -(void)changeLabelValue:(NSNotification*)notification;

name:@"label"是发送给观察者的NSNotification的名字,即只有名字为@"label"的NSNotification才能发送给这个观察者,如果为nil,那么消息中心会把object中的所有notification发送给观察者;

object:nil是发送给self的对象,假设这个object是一个NSString对象,在所执行的方法changeLabelValue:中可以这样使用它:                                NSString *str = (NSString*)[notification object];如果为空,则消息中心会把所有名字为@"label"的notification发送给观察者;

为了防御式编程,需要先检查观察者是否相应注册的函数:

if ([self respondsToSelector:@selector(changeLabelValue:)]) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(changeLabelValue:)
                                                 name:@"label"
                                               object:nil];
}

发送消息

消息中心这样发送消息:

NSNotification *notification = nil;
notification = [NSNotification notificationWithName:@"label" object:textField.text];
[[NSNotificationCenter defaultCenter] postNotification:notification];

这个notification被取了个名字叫@"label",因此可以发送给上面注册的观察者,发送的对象是一个字符串。

 NSNotification就是设计模式中的观察者模式。

使用场景

NSNotification对应于设计模式中的观察者模式,很多相互协作的类直接既要保持一致性,又要保证低耦合,这时就需要用到NSNotification在各个对象直接传递消息。

posted @ 2013-07-30 10:25  秃鹰  阅读(242)  评论(0)    收藏  举报