美文网首页面试必看
iOS开发之NSNotification

iOS开发之NSNotification

作者: 邦奇诺 | 来源:发表于2016-04-05 16:20 被阅读173次

NSNotification:一个对象能够给其他任意数量的对象广播信息。对象之间可以没有耦合关系。

上一次,我们分享了有关 KVO 的内容,但 KVO 只是一对一的关系,如果要用到一对多的关系的时候,该怎么办呢?这个时候就可以用到NSNotification(通知)

1、NSNotification 的基本知识

相关类:
1、NSNotification(通知):封装了要广播的信息。
2、NSNotificationCenter(通知中心):管理注册接收消息对象,广播消息。
3、observer(观察者):需要监测广播信息的对象,即接收信息的对象。

2、NSNotification 的基本用法

下面举一个例子,来说明NSNotification的用法:
创建两个UIViewController:
在 viewController_01.m 中:

- (void)viewDidLoad {
    [super viewDidLoad];
    //  接收信息对象在通知中心注册,包括:信息名称、接收信息时的处理方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheme:) name:@"change" object:nil];
}

    //  实现注册的方法
- (void)changeTheme:(NSNotification *)sender {
    self.view.backgroundColor = sender.userInfo[@"color"];
}

在 viewController_02.m 中:

- (void)viewDidLoad {
    [super viewDidLoad];
    //  接收信息对象在通知中心注册,包括:信息名称、接收信息时的处理方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheme:) name:@"change" object:nil];
}

    //  实现注册的方法
- (void)changeTheme:(NSNotification *)sender {
    self.view.backgroundColor = sender.userInfo[@"color"];
}

在 viewController_03.m 中:

//  创建 viewController_03.m 的 Button 对应的方法
- (IBAction)changedColor:(UIButton *)sender {
    //  给已注册对象,发送消息,这里是一键修改背景颜色
    [[NSNotificationCenter defaultCenter] postNotificationName:@"change" object:nil userInfo:@{@"color": [UIColor lightGrayColor]}];
}

** 点击viewController_03里的button,viewcontroller_01和viewController_02的backgroundColor就会改变**

通过NSNotification,可以很容易的完成一对多的消息发送!

相关文章

  • iOS开发之NSNotification

    NSNotification:一个对象能够给其他任意数量的对象广播信息。对象之间可以没有耦合关系。 上一次,我们分...

  • iOS开发 - NSNotification原理理解

    转载自:iOS开发 - NSNotification原理理解[http://cloverkim.com/ios_n...

  • iOS 事件监听

    iOS监听某些事件的方法 通知(NSNotificationCenter\NSNotification)任何对象之...

  • iOS监听某些事件的方法

    iOS监听某些事件的方法 通知(NSNotificationCenter\NSNotification)任何对象之...

  • ios 常见的几种逆向传值方式

    在iOS开发中,常见的几种逆向传值方式,有代理(delegate)、通知(NSNotification),bloc...

  • iOS中常见的几种逆向传值方式

    在iOS开发中,常见的几种逆向传值方式,有代理(delegate)、通知(NSNotification),bloc...

  • NSNotification 通知

    +++Categories = ["iOS",]Tags = ["iOS","NSNotification",]d...

  • iOS之NSNotification

    通知(NSNotification),是iOS开发中一种重要的设计模式,它的实质是程序内部提供的一种广播机制。把接...

  • 自定义NSNotification

    NSNotification在iOS开发中使用频率还是比较高的,大部分都停留在使用阶段;今天详细讲解下iOS中关于...

  • 回调方式总结

    今天对ios开发中常用的几种回调方式:block、delegate与NSNotification进行一下总结,并对...

网友评论

本文标题:iOS开发之NSNotification

本文链接:https://www.haomeiwen.com/subject/mqbxlttx.html