您的位置:首页 > 移动开发 > IOS开发

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

2014-11-01 23:23 381 查看
通知机制



图示为通知机制的实现

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: