深入思考NSNotification

阅读原文

最近技术分享,想到了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注册观察者,接收通知,可以看到打印结果如下:

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

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

发送方式

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 *)modes可以使用不同的NSRunLoopMode配合来发送通知,可以看出实际上NSNotificationQueue与RunLoop的机制以及运行循环有关系,通过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 具体的代码有兴趣的同学可以自己去翻阅下,这里就不做详细的分析了。

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

Last updated