现在的位置: 首页 > 综合 > 正文

简单介绍下NSNotificationCenter

2013年09月04日 ⁄ 综合 ⁄ 共 1074字 ⁄ 字号 评论关闭

ios开发中有时会用到NSNotificationCenter,其实NSNotificationCenter的原理是一个观察者模式,包括了观察者的注册、通知及删除等。

获得NSNotificationCenter的方法只有一种,那就是[NSNotificationCenter defaultCenter],通过调用静态方法defaultCenter就可以获取这个通知中心的对象了,而NSNotificationCenter是一个单例模式,而这个通知中心的对象会一直存在于一个应用的生命周期。

很多消息都会通过通知中心分发,比如你想在键盘收起时做一些事情,就可以写一个方法,比如叫keyboardDidHide:,然后只需要加上如下代码:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];

这样,就可以在键盘收起的时候调用当前类的keyboardDidHide:方法了。类似UIKeyboardDidHideNotification这样的消息名还有很多,如UIKeyboardDidShowNotification,UIWindowDidResignKeyNotification等等。

我们如果想定制自己的消息名也是很简单的

NSNotificationCenter *notifyCenter = [NSNotificationCenter defaultCenter];
    [notifyCenter addObserver:self selector:@selector(等到通知后调用的方法) name:你的消息名,必须是NSString类型 object:nil];

而发送这个消息其实也只需几行代码

NSNotificationCenter * notifyCenter = [NSNotificationCenter defaultCenter];
    NSNotification *nnf = [NSNotification notificationWithName:你的消息名,必须是NSString类型 object:新建一个NSNotification需要的的对象];
    [notifyCenter postNotification:nnf];

当postNotification方法调用后,之前添加的观察者就会收到通知了,当然,前提是这两个消息名要相同。

抱歉!评论已关闭.