美文网首页iOS知识点~m
iOS 通知中心的总结

iOS 通知中心的总结

作者: MasterChen | 来源:发表于2016-10-21 00:30 被阅读1005次

iOS 提供了一种 “同步的” 消息通知机制NSNotificationCenter,观察者只要向消息中心注册, 即可接受其他对象发送来的消息,消息发送者和消息接受者两者可以互相一无所知,完全解耦。
消息机制常常用于在向服务器端请求数据或者提交数据的场景,在和服务器端成功交互后,需要处理服务器端返回的数据,或发送响应消息等,就需要用到消息机制

一、通知相关的类

  1. NSNotification 这个类可以理解为一个消息对象,其中包含三个属性
    @property (readonly, copy) NSNotificationName name;//消息对象的唯一标识,用于辨别消息对象。
    @property (nullable, readonly, retain) id object;//
    @property (nullable, readonly, copy) NSDictionary *userInfo;//用来传递消息

NSNotification的初始化方法:
<pre><code> - (instancetype)initWithName:(NSNotificationName)name object:(nullable id)object userInfo:(nullable NSDictionary *)userInfo NS_AVAILABLE(10_6, 4_0) NS_DESIGNATED_INITIALIZER;</code></pre>

<pre><code>- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;</code></pre>

<pre><code>+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject;</code></pre>

<pre><code>+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;</code></pre>

<pre><code>- (instancetype)init //不能调用 /NS_UNAVAILABLE/; /* do not invoke; not a valid initializer for this class */</code></pre>
注意:官方文档有明确的说明,不可以使用init进行初始化

  1. NSNotificationCenter这个类是通知中心,用单例设计,每个应用程序都会有一个默认的通知中心,用于调度通知的发送和接受。
  • 添加一个观察者,可以为它指定一个方法,名字和对象。接收到通知时,执行方法。
    <pre><code> - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;</code></pre>

参数解析:Observer:(谁来接受通知消息);selector(方法选择,执行哪个方法); name:(通知的名称,也可以说是通知消息的标识,按照这个来区分是否接受通知);object:(接受谁的通知(进行筛选),用这个参设置,nil为接受所有文件 发送的通知)。

  • 发送通知消息的方法
    <pre><code>- (void)postNotification:(NSNotification *)notification;</code></pre>
    <pre><code>- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;</code></pre>
    <pre><code>- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;</code></pre>

参数解析:Name:(通知标识,与注册通知是的标识对应);object:(发送方);userInfo:(重点说一下,这是一个字典类型的对象,可以把需要传递 的值放进这个字典里)

  • 移除通知的方法
    <pre><code>- (void)removeObserver:(id)observer;</code></pre>
    <pre><code>- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;</code></pre>

注意:1.如果发送的通知指定了object对象,那么观察者接收的通知设置的object对象与其一样,才会接收通知。但是接收通知如果将这个参数设置为nil则会接收一切通知。
2.观察者的SEL函数指针可以有一个参数,参数就是发送的消息对象本身,可以通过这个参数取到消息对象的usetInfo,实现传值。

二、通知的使用流程

要想完成一个通知,主要有分三个执行步骤,而且是按顺序来的
顺序很重要,顺序很重要,顺序很重要,重要的事情说三遍
1.要保证注册通知在发送消息之前

  1. 首先,在需要接收通知的地方注册观察者,比如
    <pre>
    //获取通知中心单例对象
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者,name和object设置为nil,表示接收一切通知
    [center addObserver:self selector:@selector(notice:) name:@"aha" object:nil];
    </pre>
  2. 然后,在我们需要时发送通知消息
    <pre>
    //创建消息对象
    NSNotification *notification = [[NSNotification alloc]initWithName:@"aha" object:@"hah" userInfo:@{@"我是消息":@"hello"}];
    //使用通知中心发送通知
    [[NSNotificationCenter defaultCenter]postNotification:notification];</pre>
  3. 最后移除通知
    <pre>
    //移除通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"aha" object:nil];
    </pre>

三、通知知识注意事项及拓展

  1. 通知一般用在反向传值,如果要实现正向传值则必须保证:注册通知在发送通知之前实现
    可以参考:Mazy_ma的博客:iOS-通知正向传值问题

  2. 多个监听者监听同一个消息时:
    监听同一条通知的多个观察者,在通知到达时,它们执行回调的顺序是不确定的,所以我们不能去假设操作的执行会按照添加观察者的顺序来执行

  3. 关于注册监听者,还有一个需要注意的问题是,每次调用addObserver时,都会在通知中心重新注册一次,即使是同一对象监听同一个消息,而不是去覆盖原来的监听。这样,当通知中心转发某一消息时,如果同一对象多次注册了这个通知的观察者,则会收到多个通知。

  4. 默认的通知是同步的:
    代码如下:
    <pre>
    -(void)viewDidLoad {
    [super viewDidLoad];
    //注册通知观察者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(comeTrueNotification:) name:kNotificationName object:@"wow"];
    UIButton *sendNoticeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [sendNoticeBtn setFrame:CGRectMake(100, 100, 100, 100)];
    [sendNoticeBtn setBackgroundColor:[UIColor cyanColor]];
    [sendNoticeBtn setTitle:@"sendBtn" forState:UIControlStateNormal];
    [self.view addSubview:sendNoticeBtn];
    [sendNoticeBtn addTarget:self action:@selector(sendNoticeBtnDown) forControlEvents:UIControlEventTouchUpInside];

     NSLog(@"%d,%@,viewDidLoad",__LINE__,[NSThread currentThread]);
    

}

-(void)comeTrueNotification:(NSNotification *)notification {
NSString *message = notification.object;
//执行消息方法
NSLog(@"%d,%@,%@",LINE,[NSThread currentThread],message);

    sleep(5);

    NSLog(@"%d,%@,comeTrueNotification",__LINE__,[NSThread mainThread]);

}
-(void)sendNoticeBtnDown {
//发送消息
[[NSNotificationCenter defaultCenter]postNotificationName:kNotificationName object:@"wow"];

    NSLog(@"%d,%@,sendNoticeBtnDown",__LINE__,[NSThread currentThread]);

}
</pre>
运行结果:

控制台展示.png
可以参考好文:NSNotificationCenter的同步和异步
  1. 通知异步的处理方法:(参考:NSNotificationCenter的同步和异步
  • 通知异步方法一:
    让通知事件处理方法在子线程中执行:(例如:)
    <pre>
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    sleep(5);
    });
    </pre>
  • 通知异步方法二:
    您可以通过NSNotificationQueue的enqueueNotification:postingStyle:和enqueueNotification:postingStyle:coalesceMask:forModes:方法将通告放入队列,实现异步发送,在把通告放入队列之后,这些方法会立即将控制权返回给调用对象。
    我们修改sendNoticeBtnDown事件如下:
    <pre>
    //发送消息
    NSNotification *notification = [NSNotification notificationWithName:kNotificationName object:@"wow"];
    [[NSNotificationQueue defaultQueue]enqueueNotification:notification postingStyle:NSPostASAP];
    // [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationName object:@"wow"];
    </pre>通过通知队列来管理通知,不会再造成阻塞
  1. 关于通知的移除
    虽然在 IOS 用上 ARC 后,不显示移除 NSNotification Observer 也不会出错,但是这是一个很不好的习惯,不利于性能和内存。
    注销观察者有2个方法:
    a. 最优的方法,在 UIViewController.m 中:
    <pre>-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }</pre>
    b. 单个移除:
    <pre>
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Notification_GetUserProfileSuccess" object:nil];
    </pre>注意:
    removeObserver:是删除通知中心保存的调度表一个观察者的所有入口,而removeObserver:name:object:是删除匹配了通知中心保存的调度表中观察者的一个入口。
    这个比较简单,直接调用该方法就行。例如:
    [[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
    注意参数notificationObserver为要删除的观察者,一定不能置为nil。

参考:iOS NSNotification的使用
IOS 消息机制(NSNotificationCenter)

相关文章

  • iOS 通知中心的总结

    iOS 提供了一种 “同步的” 消息通知机制NSNotificationCenter,观察者只要向消息中心注册, ...

  • IOS通知中心

    通知中心(NSnotificationCenter): 由发送者1或者多个发送者n 通过发送一个通知到通知中心,接...

  • iOS - 通知中心

    通知中心:NSNotificationCentereg:农村大喇叭发送广播 条件:在大喇叭广播之前要有村民(对象-...

  • iOS 通知中心

    不要随随便便就是用通知,不懂的话对性能影响挺大的.虽然用起来很方便. 下边是理论知识: 即使在适合使用通告的场合下...

  • iOS 通知中心

    What is NSNotificationCenter? NSNotificationCenter是一种一对多的...

  • iOS通知中心

    http://potter528.bj.bdysite.com 如果播放器播放完毕后通知中心通知对象,执行方法选择...

  • iOS通知中心

    有关的类 NSNotification NSNotificationCenter NSNotification N...

  • iOS 通知 与 通知中心

    iOS 通知中心:自己实现了一套消息机制,可以跨页面调用 类似Unity的SendMessage,是订阅、发布者模...

  • IOS 通知中心NotificationCenter

  • iOS通知中心-NSNotificationCenter

    NSNotification是iOS中一个调度消息通知的类,使用极为方便,但是劝各位还是慎用,当你日后修改工程的时...

网友评论

本文标题:iOS 通知中心的总结

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