iOS开发 使用NSNotificationCenter

在iOS开发中,类与类之间的通信方式有很多:delegate、block、KVO,还有就是NSNotificationCenter。使用NSNotificationCenter的好处就是可以让多个无引用关系的对象进行通信。


注册通知

[[NSNotificationCenter defaultCenter] addObserver:observer selector:SEL name:name object:object];
使用以上代码实现注册一个通知,其中 observer 代表接收通知的对象,SEL 指收到通知时执行的方法,name 表示通知的名称,是通知的唯一标示符,而设置 object 可以指定一个具体的消息发送者,不设置的话代表接收者可以接收到任意发送者的通知。

一般而言,接收到通知时调用方法的格式是:

- (void)myNotification:(NSNotification *)notification
{
    
}

其中,NSNotification有三个成员变量:NSString *name; id object; NSDictionary *userInfo; 使用[notification object]可以获取到传递的对象,userInfo 表示附加消息。


发送通知

[[NSNotificationCenter defaultCenter] postNotificationName:name object:object];
发送者可以使用以上代码广播一个通知。若是注册通知时设置了 object,则只有发送通知的 object参数与之相同,接收者才能接收到该发送者发送的通知。

使用以下代码可以发送一个带有附加消息的通知:

[[NSNotificationCenter defaultCenter] postNotificationName:name object:object userInfo:userInfo];


移除通知

接收者不再接收通知时,记住要移除通知:

[[NSNotificationCenter defaultCenter] removeObserver:observe name:name object:object];

系统通知

如果你想对系统的某些事件做出响应,则只需注册一个系统通知即可,例如注册一个键盘出现的通知:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardDidShow:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];
当键盘出现时,self 就会调用keyboardDidShow:方法。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值