深入思考NSNotification

作者: Tracy_ljs | 来源:发表于2017-03-30 17:52 被阅读1706次

最近技术分享,想到了NSNotification这个话题,大家可能觉得平时项目中用通知很简单啊,并没有什么高深的东西吧,其实我们深入了去看,苹果官方api还是介绍了一些通知更复杂的用法,今天就来和大家探讨一下NSNotification进阶。

先来看看苹果官方文档是这样写的:

In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.

意思就是说:

在多线程应用中,Notification在哪个线程中post,就在哪个线程中被转发,而不一定是在注册观察者的那个线程中。

这也就是说通知的发送是同步的,首先我们先思考三个问题开始我们今天的话题吧。

问题一:如何异步的发送通知
问题二:通知和Runloop的关系
问题三:如何指定线程发送通知

这三个问题看上去挺简单,如果你没有深入了解过通知,那么你的回答显然不是我想要的答案。

问题一:如何异步的发送通知

这里我们会用到NSNotificationqueue这个类,从字面意思我们可以了解到是通知队列的意思。
NSNotificationQueue通知队列,用来管理多个通知的调用。通知队列通常以先进先出(FIFO)顺序维护通。NSNotificationQueue就像一个缓冲池把一个个通知放进池子中,使用特定方式通过NSNotificationCenter发送到相应的观察者。

- (void)notifuQueue {
    
    //每个进程默认有一个通知队列,默认是没有开启的,底层通过队列实现,队列维护一个调度表
    NSNotification *notifi = [NSNotification notificationWithName:@"Notification" object:nil];
    NSNotificationQueue *queue = [NSNotificationQueue defaultQueue];

    //FIFO
    NSLog(@"notifi before");
    [queue enqueueNotification:notifi postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, nil]];
    NSLog(@"notifi after");
    
    
    NSPort *port = [[NSPort alloc] init];
    [[NSRunLoop currentRunLoop] addPort:port forMode:NSRunLoopCommonModes];
    [[NSRunLoop currentRunLoop] run];
    NSLog(@"runloop over");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifi:) name:@"Notification" object:nil];
}

首先我们去调用notifuQueue这个方法,发送通知,在viewDidLoad注册观察者,接收通知,可以看到打印结果如下:


打印.png

我们可以看到打印结果显示通知是异步执行了。

接下来解释下几个参数的意思:

发送方式

NSPostingStyle有三种类型:

typedef NS_ENUM(NSUInteger, NSPostingStyle) {
    NSPostWhenIdle = 1,
    NSPostASAP = 2,
    NSPostNow = 3  
};

NSPostWhenIdle:空闲发送通知 当运行循环处于等待或空闲状态时,发送通知,对于不重要的通知可以使用。
NSPostASAP:尽快发送通知 当前运行循环迭代完成时,通知将会被发送,有点类似没有延迟的定时器。
NSPostNow :同步发送通知 如果不使用合并通知 和postNotification:一样是同步通知。

合并通知

  • NSNotificationCoalescing也包括三种类型:
typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {
    NSNotificationNoCoalescing = 0,
    NSNotificationCoalescingOnName = 1,
    NSNotificationCoalescingOnSender = 2
};

NSNotificationNoCoalescing:不合并通知。
NSNotificationCoalescingOnName:合并相同名称的通知。
NSNotificationCoalescingOnSender:合并相同通知和同一对象的通知。

  • 通过合并我们可以用来保证相同的通知只被发送一次。
  • forModes:(nullable NSArray<NSRunLoopMode> *)modes可以使用不同的NSRunLoopMode配合来发送通知,可以看出实际上NSNotificationQueueRunLoop的机制以及运行循环有关系,通过NSNotificationQueue队列来发送的通知和关联的RunLoop运行机制来进行的。

问题二:通知和Runloop的关系

- (void)notifiWithRunloop {
    CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
        
        if(activity == kCFRunLoopEntry){
            NSLog(@"进入Runloop");
        }else if(activity == kCFRunLoopBeforeWaiting){
            NSLog(@"即将进入等待状态");
        }else if(activity == kCFRunLoopAfterWaiting){
            NSLog(@"结束等待状态");
        }
    });
    CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
    
    CFRelease(observer);
    
    NSNotification *notification1 = [NSNotification notificationWithName:@"notify" object:nil userInfo:@{@"key":@"1"}];
    NSNotification *notification2 = [NSNotification notificationWithName:@"notify" object:nil userInfo:@{@"key":@"2"}];
    NSNotification *notification3 = [NSNotification notificationWithName:@"notify" object:nil userInfo:@{@"key":@"3"}];

    [[NSNotificationQueue defaultQueue] enqueueNotification:notification1 postingStyle:NSPostWhenIdle coalesceMask:NSNotificationNoCoalescing forModes:@[NSDefaultRunLoopMode]];
    
    [[NSNotificationQueue defaultQueue] enqueueNotification:notification2 postingStyle:NSPostASAP coalesceMask:NSNotificationNoCoalescing forModes:@[NSDefaultRunLoopMode]];
    
    [[NSNotificationQueue defaultQueue] enqueueNotification:notification3 postingStyle:NSPostNow coalesceMask:NSNotificationNoCoalescing forModes:@[NSDefaultRunLoopMode]];
    
    NSPort *port = [[NSPort alloc] init];
    [[NSRunLoop currentRunLoop] addPort:port forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

先来看下打印结果,可以很清晰的看到结论:

NSConcreteNotification 0x618000051fa0 {name = notify; userInfo = {
    key = 3;
}}
2017-03-30 17:27:09.626 Notification[59492:2559004] 进入Runloop
2017-03-30 17:27:09.627 Notification[59492:2559004] NSConcreteNotification 0x618000057910 {name = notify; userInfo = {
    key = 2;
}}
2017-03-30 17:27:09.627 Notification[59492:2559004] 即将进入等待状态
2017-03-30 17:27:09.627 Notification[59492:2559004] NSConcreteNotification 0x618000051f10 {name = notify; userInfo = {
    key = 1;
}}
2017-03-30 17:27:09.627 Notification[59492:2559004] 结束等待状态
2017-03-30 17:27:09.628 Notification[59492:2559004] 即将进入等待状态
  • 我们很清晰的看到第3个通知没有进入Runloop,因为上面说了NSPostNow是立即执行,相当于通知中心发出的同步通知,所以与Runloop没有关系。
  • 其次,参数NSPostASAP的通知要快于NSPostWhenIdle的通知进入Runloop。

问题三:如何指定线程发送通知

先来看个例子:

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"current thread = %@", [NSThread currentThread]);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil];
    });
}
    
- (void)handleNotification:(NSNotification *)notification
{
    NSLog(@"current thread = %@", [NSThread currentThread]);
    
    NSLog(@"test notification");
}
    
@end

输出结果如下:

1、2017-03-30 22:05:12.856 test[865:45102] current thread = <NSThread: 0x7fbb23412f30>{number = 1, name = main}
2、2017-03-30 22:05:12.857 test[865:45174] current thread = <NSThread: 0x7fbb23552370>{number = 2, name = (null)}
3、2017-03-30 22:05:12.857 test[865:45174] test notification
  • 可以看到,虽然我们在主线程中注册了通知的观察者,但在全局队列中post的Notification,并不是在主线程处理的。所以,这时候就需要注意,如果我们想在回调中处理与UI相关的操作,需要确保是在主线程中执行回调。

  • 这个时候有人要说了直接在处理通知事件的地方强制切回主线程不就行了么,对的,这是可以的,但如果我在子线程发送多个通知,注册多个不同的观察者,那你是否要在每一个通知处理的地方都去切主线程,显然这是不合理的。

  • 我们先来看下苹果官方文档的说法:

For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.

  • 这里讲到了“重定向”,就是我们在Notification所在的默认线程中捕获这些分发的通知,然后将其重定向到指定的线程中。

  • 一种重定向的实现思路是自定义一个通知队列(注意,不是NSNotificationQueue对象,而是一个数组),让这个队列去维护那些我们需要重定向的Notification。我们仍然是像平常一样去注册一个通知的观察者,当Notification来了时,先看看post这个Notification的线程是不是我们所期望的线程,如果不是,则将这个Notification存储到我们的队列中,并发送一个信号(signal)到期望的线程中,来告诉这个线程需要处理一个Notification。指定的线程在收到信号后,将Notification从队列中移除,并进行处理。

来看下官方给的demo:

@interface ViewController () <NSMachPortDelegate>
@property (nonatomic) NSMutableArray    *notifications;         // 通知队列
@property (nonatomic) NSThread          *notificationThread;    // 期望线程
@property (nonatomic) NSLock            *notificationLock;      // 用于对通知队列加锁的锁对象,避免线程冲突
@property (nonatomic) NSMachPort        *notificationPort;      // 用于向期望线程发送信号的通信端口
    
@end
    
@implementation ViewController
    
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"current thread = %@", [NSThread currentThread]);
    
    // 初始化
    self.notifications = [[NSMutableArray alloc] init];
    self.notificationLock = [[NSLock alloc] init];
    
    self.notificationThread = [NSThread currentThread];
    self.notificationPort = [[NSMachPort alloc] init];
    self.notificationPort.delegate = self;
    
    // 往当前线程的run loop添加端口源
    // 当Mach消息到达而接收线程的run loop没有运行时,则内核会保存这条消息,直到下一次进入run loop
    [[NSRunLoop currentRunLoop] addPort:self.notificationPort
                                forMode:(__bridge NSString *)kCFRunLoopCommonModes];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processNotification:) name:@"TestNotification" object:nil];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil];
    
    });
}
    
- (void)handleMachMessage:(void *)msg {
    
    [self.notificationLock lock];
    
    while ([self.notifications count]) {
        NSNotification *notification = [self.notifications objectAtIndex:0];
        [self.notifications removeObjectAtIndex:0];
        [self.notificationLock unlock];
        [self processNotification:notification];
        [self.notificationLock lock];
    };
    
    [self.notificationLock unlock];
}
    
- (void)processNotification:(NSNotification *)notification {
    
    if ([NSThread currentThread] != _notificationThread) {
        // Forward the notification to the correct thread.
        [self.notificationLock lock];
        [self.notifications addObject:notification];
        [self.notificationLock unlock];
        [self.notificationPort sendBeforeDate:[NSDate date]
                                   components:nil
                                         from:nil
                                     reserved:0];
    }
    else {
        // Process the notification here;
        NSLog(@"current thread = %@", [NSThread currentThread]);
        NSLog(@"process notification");
    }
}
    
@end

运行结果如下:

1、2017-03-30 23:38:31.637 test[1474:92483] current thread = <NSThread: 0x7ffa4070ed50>{number = 1, name = main}
2、2017-03-30 23:38:31.663 test[1474:92483] current thread = <NSThread: 0x7ffa4070ed50>{number = 1, name = main}
3、2017-03-30 23:38:31.663 test[1474:92483] process notification

可以清晰的看到,在异步线程中发送了一条通知,在主线程中捕获。
但是这种实现方案苹果也也提出了他的局限性:

This implementation is limited in several aspects. First, all threaded notifications processed by this object must pass through the same method (processNotification:). Second, each object must provide its own implementation and communication port. A better, but more complex, implementation would generalize the behavior into either a subclass of NSNotificationCenter or a separate class that would have one notification queue for each thread and be able to deliver notifications to multiple observer objects and methods.

解决方案

github上有人提出了一种解决方案,这里贴下链接https://github.com/zachwangb/GYNotificationCenter
它是重新写一个 Notification 的管理类,想要达到的效果有两个:

  • 能够方便的控制线程切换
  • 能够方便的remove observer

具体的代码有兴趣的同学可以自己去翻阅下,这里就不做详细的分析了。

写了这么多,如果你喜欢,就请点个赞吧,谢谢!

相关文章

  • 深入思考NSNotification

    最近技术分享,想到了NSNotification这个话题,大家可能觉得平时项目中用通知很简单啊,并没有什么高深的东...

  • NSNotification 深入探究

    使用背景 通常情况下,我们一个对象想要调用另外一个对象的方法,便是向这个对象传递消息,那么有个前提是,我们需要能找...

  • 深入NSNotification(iOS)

    NSNotification顾名思义就是通知的作用,一个对象通知另外一个对象,可以用来传递参数、通信等作用,与de...

  • 深入理解iOS NSNotification

    NSNotification在平时开发中使用非常频繁。网上关于NSNotification介绍大多是停留在用法的介...

  • 深入理解iOS NSNotification

    NSNotification在平时开发中使用非常频繁。网上关于NSNotification介绍大多是停留在用法的介...

  • 深入理解iOS NSNotification

    自己设计一个通知中心核心就是操作两个Table及一个链表。1、先创建一个通知中心的单例,里边有一个NSHashTa...

  • NSNotification

    发通知 NSNotification *deleteMyCommemtN =[NSNotification not...

  • 通知使用

    创建对象 NSNotification *notification =[NSNotification notifi...

  • iOS通知中心

    有关的类 NSNotification NSNotificationCenter NSNotification N...

  • 通知中心(NSNotificationCenter)总结

    一、简介 1. NSNotification 理解 NSNotification@property (readon...

网友评论

  • litt1err:这样是不是通知队列应该全局维护的
  • 755f3c191771:你好,第一点实现异步的发送通知,为什么那样做就能实现呢?
    Tracy_ljs:@南海孤鱼 看下官方文档哈
  • CoderHG:大神,你们学习东西怎么会这么细啊.这些知识点,你们是怎么考虑到的?我一般都考虑不到这么细.求教.:+1:
    Tracy_ljs:@CoderHG 看苹果官方的文档啊,这些苹果文档都会说明的
  • 天口三水羊:900阅读 168喜欢 有点。。
    Tracy_ljs:@天口三水羊 有点受欢迎吗
  • 红烧大鸡腿:楼主,我想知道这个有没有gitgub的链接😀
    红烧大鸡腿:@tree_one 哦,看见了
    Tracy_ljs:@红烧大鸡腿 链接贴出来了哈
  • 我还没想好12138:handleMachMessage这个函数是干嘛的,什么时候调用呢
    Persen:@tree_one 这个函数是在实现port.delegate 调用,博主博客写的有隐藏呀:smile:
    Tracy_ljs:@我还没想好12138 这个是当你通过端口发送信号的回调,作用是去切换你期望的线程
  • 陈藩:写的真好,有让我心里开了一块空地的感觉。
    陈藩:@tree_one 之前没有思考这么多啊,也没碰到什么问题。
    Tracy_ljs:@寒塘秋客 此话怎讲
  • PGOne爱吃饺子:异步的发送通知,只要开启一个线程,发送一个通知不就是异步发送通知了么,感觉你异步发送通知的方式实现起来是不是有点麻烦啊
    Tracy_ljs:@4140d18ee6fc 首先通过通知中心发送的通知是同步的,其次如果你需求里需要发很多个通知,有些通知名是相同的,用通知队列可以合并这些相同名称的通知
    PGOne爱吃饺子:重复发送通知是什么意义啊,我不就是开了一个异步线程,发了一条通知么,怎么还会重复发送通知么
    Tracy_ljs:@4140d18ee6fc 这种通过队列的方式可以合并相同或者类似的通知,提高性能,而你说的那个会发重复通知,显然是不合适的
  • PGOne爱吃饺子:大神 您好,请问您说的这个 “如何异步的发送通知”,这句话是什么意思,你可以说的明白一些么
    Tracy_ljs:@4140d18ee6fc 区别于通过通知中心发出的同步通知,通过通知队列发出的是异步通知

本文标题:深入思考NSNotification

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