iOS设计模式 - 通知机制(Notification)

通知机制


                                             图示为通知机制的实现

1、通知中心(NSNotificationCenter)

每个运行中的application都有一个NSNotificationCenter的成员变量,它的功能就类似公共栏. 发布自己想要发送的notification。我们把这些注册对象叫做 observer. 其它的一些对象会给center发送notifications。

每个对象可以通过NSNotificationCenter把自己想要发送的notifications转发给所有对该notification感兴趣的对象(observer)。

很多的标准Cocoa类会发送notifications: 在改变size的时候,Window会发送notification; 


2. 添加监听

<span style="font-size:14px;"> - (void)addObserver:(id)anObserver selector:(SEL)aSelector name:(NSString *)notificationName object:(id)anObject</span>
anObserver:监听者,即谁将要接收这个通知

aSelector:接收到通知后,回调监听器这个方法,并且把通知对象当作参数传递

aName:通知的名称,如果是nil,无论通知的名称是什么,监听器都能收到

anObject :通知发布者,如果是nil,监听器都能听到

3. 发送通知

<span style="font-size:14px;"> - (void)postNotificationName:(NSString *)aName object:(id)anObject</span>
postNotificationName 通知的名称

object 发布通知的对象

userInfo 发布的内容

在开发中可以根据userInfo知道通知对象的一些属性

4.注意

在添加监听的类中需要重写dealloc方法,

<span style="font-size:14px;">- (void)dealloc
{
</span><pre name="code" class="objc"><span style="font-size:14px;">  [NSNotificationCenter defaultCenter] removeObserver:self];
}</span>

 
二 、 使用通知监听键盘的改变 

1. 自定义事件

监听名为next的事件

<span style="font-size:14px;">[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(next:) name:@"next" object:nil];</span>
发送事件

<span style="font-size:14px;"> [[NSNotificationCenter defaultCenter] postNotificationName:@"next" object:self userInfo:@{name: @"GG"}];</span>

<span style="font-size:14px;">实现监听方法
- next(NSNotification *)note
{
     NSLog(@"%@",note.info[@"name"]);
}</span>

重写dealloc,删除通知

<span style="font-size:14px;">- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}</span>


2. 监听系统事件

监听键盘改变

<span style="font-size:14px;">[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) 
                       name:UITextFieldTextDidChangeNotification object:_phoneField];</span>


实现监听方法

<span style="font-size:14px;">- (void)textChange
{
    _addBtn.enabled = (_nameField.text.length && _phoneField.text.length);
}
</span>

重写dealloc,删除通知

<span style="font-size:14px;">- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}</span>





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值