美文网首页
iOS通知(Notification)使用浅谈

iOS通知(Notification)使用浅谈

作者: 过客又见过客 | 来源:发表于2017-12-23 18:30 被阅读27次

iOS的通知(Notification)基本上都是以sync(同步)的方式发送的,也就是说当发送通知出去以后会先阻塞当前线程,等到所有注册该通知者接收到此通知并在当前线程进行完相对应的处理后,程序才会继续往下执行。

为了测试这点,我们可以创建BYNotifyPoster和BYNotifyReceiver两个类,分别负责发送和接收通知。在测试过程,我们分别在主线程和异步线程各发送一次通知,测试接收者执行的情况。

BYNotifyReceiver

//
//  BYNotifyReceiver.h
//  NotificationTest
//
//  Created by Beryter on 2017/12/23.
//  Copyright © 2017年 Beryter. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface BYNotifyReceiver : NSObject

@end


#import "BYNotifyReceiver.h"

@implementation BYNotifyReceiver

- (instancetype)init
{
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"BYNotificationTest" object:nil];
    }
    return self;
}

/*!
 * @brief   接收通知(BYNotificationTest)
 * @param   note NSNotification通知对象
 */
- (void)handleNotification:(NSNotification *)note
{
    if ([[NSThread currentThread] isMainThread]) {
        NSLog(@"接收到通知 - BYNotificationTest,主线程,开始处理相关逻辑");
    } else {
        NSLog(@"接收到通知 - BYNotificationTest,异步线程,开始处理相关逻辑");
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"BYNotificationTest" object:nil];
}

@end

BYNotifyPoster

//
//  BYNotifyPoster.h
//  NotificationTest
//
//  Created by Beryter on 2017/12/23.
//  Copyright © 2017年 Beryter. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface BYNotifyPoster : NSObject

- (void)postNotification;

@end

#import "BYNotifyPoster.h"

@implementation BYNotifyPoster

/*!
 * @brief 发送通知BYNotificationTest
 */
- (void)postNotification
{
    NSLog(@"准备发送通知 - BYNotificationTest");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BYNotificationTest" object:nil];
    NSLog(@"BYNotificationTest - 通知发送完毕,继续往下执行");
    // TODO:发送通知完毕后,继续执行
}

@end

我们在测试ViewController中加入以下代码:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    NSLog(@"------------主线程发送通知---------------");
    [self.poster postNotification];
    
    sleep(5);//延迟五秒
    
    NSLog(@"------------异步线程发送通知--------------");
     __weak typeof(self) weakSelf = self;
    dispatch_queue_t queue = dispatch_queue_create("NOTIFICATION_TEST_QUEUE", NULL);
    dispatch_async(queue, ^{
        [weakSelf.poster postNotification];
    });
}

运行后,测试结果如下:

2017-12-23 14:25:37.951231+0800 NotificationTest[4327:320244] ------------主线程发送通知---------------
2017-12-23 14:25:37.951388+0800 NotificationTest[4327:320244] 准备发送通知 - BYNotificationTest
2017-12-23 14:25:37.951496+0800 NotificationTest[4327:320244] 接收到通知 - BYNotificationTest,主线程,开始处理相关逻辑
2017-12-23 14:25:37.951604+0800 NotificationTest[4327:320244] BYNotificationTest - 通知发送完毕,继续往下执行
2017-12-23 14:25:42.952721+0800 NotificationTest[4327:320244] ------------异步线程发送通知--------------
2017-12-23 14:25:42.953099+0800 NotificationTest[4327:320290] 准备发送通知 - BYNotificationTest
2017-12-23 14:25:42.953337+0800 NotificationTest[4327:320290] 接收到通知 - BYNotificationTest,异步线程,开始处理相关逻辑
2017-12-23 14:25:42.953516+0800 NotificationTest[4327:320290] BYNotificationTest - 通知发送完毕,继续往下执行

根据运行后打印的log日志我们可以看到,BYNotifyPoster在发送完通知后,会等待所有被通知到的对象处理完相关事情后才会继续向下执行,确实是以sync(同步)的方式进行的。我们在看BYNotifyReceiver在接收到通知后打印的log日志,可以发现相关处理逻辑所在的线程和发送通知所在的线程是同一个线程。一句话就是,Notification是以sync(同步)的方式发送的,也就是说当发送通知出去以后会先卡住当前线程,等到所有注册该通知者接收到此通知并在当前线程(即发出通知的线程)进行完相对应的处理后,程序才会继续往下执行。

注册通知的另一个方法

我们继续往下看,在注册通知的API中或许我们还会发现一个比较有趣的API,如下:

- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    // The return value is retained by the system, and should be held onto by the caller in
    // order to remove the observer with removeObserver: later, to stop observation.

我们可以看到,此方法在给通知注册观察者的时候,加入了queue和block,简化了代码,同样也使代码逻辑更加紧凑,代码的可读性也更高。它并没有指定observer,而是返回一个observer。在这里,如果指定queue,block的执行将在你指定的queue中执行,若没有指定queue,block的执行将在post消息线程中执行。注意,此处block会引起循环引用,使用过程中要使用weakSelf。关键代码如下:

//将BYNotifyReceiver中代码调整如下
- (instancetype)init
{
    if (self = [super init]) {
   
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        queue.name = @"NOTIFICATION_HANDLE_QUEUE";
        __weak typeof(self) weakSelf = self;
       _notificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:@"BYNotificationTest" object:nil queue:queue usingBlock:^(NSNotification * _Nonnull note) {
           [weakSelf testQueueNotification];
        }];
    }
    return self;
}

- (void)testQueueNotification
{
   [NSThread sleepForTimeInterval:5];//阻塞当前线程5秒
    if ([[NSThread currentThread] isMainThread]) {
        NSLog(@"接收到通知 - BYNotificationTest,主线程,开始处理相关逻辑,currentQueue = %@",[NSOperationQueue currentQueue].name);
    } else {
        NSLog(@"接收到通知 - BYNotificationTest,异步线程,开始处理相关逻辑,currentQueue = %@",[NSOperationQueue currentQueue].name);
    }
    // 注意移除通知的方式,参数为notificationObserver,而不是self
    [[NSNotificationCenter defaultCenter] removeObserver:self.notificationObserver];
}

//ViewController中代码
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"------------主线程发送通知---------------");
    [self.poster postNotification];
    self.receiver = nil;
}

而log日志如下,不用过多解释请仔细看:

2017-12-23 16:37:21.559728+0800 NotificationTest[7607:678009] ------------主线程发送通知---------------
2017-12-23 16:37:21.559865+0800 NotificationTest[7607:678009] 准备发送通知 - BYNotificationTest
2017-12-23 16:37:26.565126+0800 NotificationTest[7607:678048] 接收到通知 - BYNotificationTest,异步线程,开始处理相关逻辑,currentQueue = NOTIFICATION_HANDLE_QUEUE
2017-12-23 16:37:26.565565+0800 NotificationTest[7607:678009] BYNotificationTest - 通知发送完毕,继续往下执行

异步通知的实现

如何实现异步通知呢?要想真正做到async(异步)发送通知,则必须使用NSNotificationQueue。
一般来讲,这个是为了合并多个通知一起发送时使用的,当然也能用作async发送通知。其中有几个比较重要的点,要知道。

NSPostingStyle用来决定何时发送通知。

typedef NS_ENUM(NSUInteger, NSPostingStyle) {
    NSPostWhenIdle = 1,  //当前runloop处于空闲或者waiting状态时post
    NSPostASAP = 2,      //当前runloop结束时post
    NSPostNow = 3        //立即post,使用此模式相当于sync!
};

NSNotificationCoalescing决定是否将多个通知进行合成,然后是以哪种方式合成。

typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {
    NSNotificationNoCoalescing = 0,        //不合并
    NSNotificationCoalescingOnName = 1,    //合并name(名称)相同的通知
    NSNotificationCoalescingOnSender = 2   //合并sender(发送者)相同的通知
};

还可以设定runloop mode。如果设定了runloop model则只会在特定的runloop mode下才会进行发送通知。

相关代码如下:

BYNotifyReceiver.m

- (instancetype)init
{
    if (self = [super init]) {
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAsyncNotification:) name:@"BYAsyncNotificationTest" object:nil];
    }
    return self;
}

- (void)handleAsyncNotification:(NSNotification *)note
{
    if ([[NSThread currentThread] isMainThread]) {
        NSLog(@"接收到通知 - BYAsyncNotificationTest,主线程,开始处理相关逻辑,currentQueue = %@",[NSOperationQueue currentQueue].name);
    } else {
        NSLog(@"接收到通知 - BYAsyncNotificationTest,异步线程,开始处理相关逻辑,currentQueue = %@",[NSOperationQueue currentQueue].name);
    }
}

BYNotifyPoster.m

/*!
 * @brief 异步发送通知
 */
- (void)asyncPostNotification
{
    NSLog(@"准备发送通知 - BYAsyncNotificationTest");
    NSNotification *asyncNotification = [NSNotification notificationWithName:@"BYAsyncNotificationTest" object:nil];
    [[NSNotificationQueue defaultQueue] enqueueNotification:asyncNotification postingStyle:NSPostASAP];
    NSLog(@"BYAsyncNotificationTest - 通知发送完毕,继续往下执行");
    // TODO:发送通知完毕后,继续执行
    [self testAsync];
}

- (void)testAsync
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

ViewController.m

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"------------主线程发送通知---------------");
    [self.poster asyncPostNotification];
}

运行后,打印Log如下,答案一目了然:

2017-12-23 17:58:24.080311+0800 NotificationTest[9651:900465] ------------主线程发送通知---------------
2017-12-23 17:58:24.080736+0800 NotificationTest[9651:900465] 准备发送通知 - BYAsyncNotificationTest
2017-12-23 17:58:24.080926+0800 NotificationTest[9651:900465] BYAsyncNotificationTest - 通知发送完毕,继续往下执行
2017-12-23 17:58:24.081192+0800 NotificationTest[9651:900465] testAsync
2017-12-23 17:58:24.081644+0800 NotificationTest[9651:900465] 接收到通知 - BYAsyncNotificationTest,主线程,开始处理相关逻辑,currentQueue = NSOperationQueue Main Queue

至于如何合并通知,这里暂时不再讲了,测试代码就无需上传了,留给想玩的同志们去玩。如果通知带有userinfo参数,此时通知被合并,userinfo又如何处理呢,是否也会被合并呢,这个地方是比较有意思的。如果被合并将会是什么样子呢?如果不被合并,那通知接受者收到的userinfo中又是什么呢?

本文为原创文章,转载请注明出处。

可加群一起交流共同学习:801216530。

相关文章

网友评论

      本文标题:iOS通知(Notification)使用浅谈

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