架构师之路OC语言特性iOS developer

深入思考NSNotification

2017-03-30  本文已影响1706人  Tracy_ljs

最近技术分享,想到了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:一样是同步通知。

合并通知

typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {
    NSNotificationNoCoalescing = 0,
    NSNotificationCoalescingOnName = 1,
    NSNotificationCoalescingOnSender = 2
};

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

问题二:通知和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] 即将进入等待状态

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

先来看个例子:

@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

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.

来看下官方给的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 的管理类,想要达到的效果有两个:

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

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

上一篇下一篇

猜你喜欢

热点阅读