简单介绍下NSNotificationCenter

http://blog.csdn.net/volcan1987/article/details/6701593

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方法调用后,之前添加的观察者就会收到通知了,当然,前提是这两个消息名要相同。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值