NSNotification 的细节

通知中心对于iOS开发者最熟悉不过了,它实现了一对多的消息传递,可以实现跨页面传递。
我们都知道NSNotification 是线程同步的,但是有时候却很容易忽视线程同步这个特性带来的问题。
比如说下面这段代码:

- (void)notification {
    NSLog(@"通知开始了!");
    [[NSNotificationCenter defaultCenter] postNotificationName:kDeviceNameDidChangedNotification object:nil];
    NSLog(@"通知结束了!");
}

然后在接收通知的地方模拟一个耗时的操作:

- (void)test:(NSNotification *)notify {
    NSLog(@"模拟耗时操作");
    [NSThread sleepForTimeInterval:5.0f];
    NSLog(@"耗时操作结束");
}

这时候我们看到控制台打印结果:

2018-09-01 14:22:16.380 通知开始了!
2018-09-01 14:22:16.385 模拟耗时操作
2018-09-01 14:22:21.290 耗时操作结束!
2018-09-01 14:22:21.300 通知结束了!

这个结果看上去似乎是有点奇怪的,因为我们选用Notification的原因之一就是它是一个单向发送不会产生回调的方式(相比较于:delegateblock)。但是结果看上去仍然不得不等待“接收方”处理完毕,才能继续执行剩下的逻辑。
但是略微思考一下就能很快明白,这正是因为notification线程同步的特性导致的,在主线程发出通知,然后接受方在主线程处理逻辑。

那么现在就引出一个问题,notification和线程同步之间到底是什么关系呢?

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

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,就在哪个线程中被转发,而不一定是在注册观察者的那个线程中。

那如果我们的Notification是在二级线程中post的,如何能在主线程中对这个Notification进行处理呢?或者换个提法,如果我们希望一个Notification的post线程与转发线程不是同一个线程,应该怎么办呢?我们看看官方文档是怎么说的:

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从队列中移除,并进行处理。

官方文档已经给出了示例代码,在此借用一下,以测试实际结果:

@interface ViewController () 
@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

运行后,其输出如下:

2015-03-11 23:38:31.637 test[1474:92483] current thread = {number = 1, name = main}
2015-03-11 23:38:31.663 test[1474:92483] current thread = {number = 1, name = main}
2015-03-11 23:38:31.663 test[1474:92483] process notification

可以看到,我们在全局dispatch队列中抛出的Notification,如愿地在主线程中接收到了。

这种实现方式的具体解析及其局限性大家可以参考官方文档Delivering Notifications To Particular Threads,在此不多做解释。当然,更好的方法可能是我们自己去子类化一个NSNotificationCenter,或者单独写一个类来处理这种转发。

而且官方文档告诉我们,NSNotificationCenter是一个线程安全类,我们可以在多线程环境下使用同一个NSNotificationCenter对象而不需要加锁。原文在Threading Programming Guide中,具体如下:

The following classes and functions are generally considered to be thread-safe. You can use the same instance from multiple threads without first acquiring a lock.

NSArray
...
NSNotification
NSNotificationCenter
...
那我们为了避免通知的线程等待,是不是可以选择在子线程发通知呢?

我们再看下面的这个例子:

#pragma mark - Poster

@interface Poster : NSObject

@end

@implementation Poster

- (instancetype)init
{
   self = [super init];

   if (self)
    {
        [self performSelectorInBackground:@selector(postNotification) withObject:nil];
    }

    return self;
}

- (void)postNotification
{
    [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
}

@end

#pragma mark - Observer

@interface Observer : NSObject
{
    Poster  *_poster;
}

@property (nonatomic, assign) NSInteger i;

@end

@implementation Observer

- (instancetype)init
{
    self = [super init];

    if (self)
    {
        _poster = [[Poster alloc] init];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil];
    }

    return self;
}

- (void)handleNotification:(NSNotification *)notification
{
   NSLog(@"handle notification begin");
    sleep(1);
    NSLog(@"handle notification end");

    self.i = 10;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    NSLog(@"Observer dealloc");
}

@end

#pragma mark - ViewController

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    __autoreleasing Observer *observer = [[Observer alloc] init];
}

@end

这段代码是在主线程添加了一个TEST_NOTIFICATION通知的监听者,并在主线程中将其移除,而我们的NSNotification是在后台线程中post的。在通知处理函数中,我们让回调所在的线程睡眠1秒钟,然后再去设置属性i值。这时会发生什么呢?我们先来看看输出结果:

2015-03-14 00:31:41.286 SKTest[932:88791] handle notification begin
2015-03-14 00:31:41.291 SKTest[932:88713] Observer dealloc
2015-03-14 00:31:42.361 SKTest[932:88791] handle notification end
(lldb)
// 程序在self.i = 10处抛出了"Thread 6: EXC_BAD_ACCESS(code=EXC_I386_GPFLT)"

经典的内存错误,程序崩溃了。其实从输出结果中,我们就可以看到到底是发生了什么事。我们简要描述一下:

  1. 当我们注册一个观察者是,通知中心会持有观察者的一个弱引用,来确保观察者是可用的。
  2. 主线程调用dealloc操作会让Observer对象的引用计数减为0,这时对象会被释放掉。
  3. 后台线程发送一个通知,如果此时Observer还未被释放,则会用其转出消息,并执行回调方法。而如果在回调执行的过程中对象被释放了,就会出现上面的问题。

通俗的讲就是 你在子线程发通知,默认子线程执行,这时候如果主线程把收通知的self释放了,子线程还未执行完的代码就会出问题。
正常情况是主线程发通知,主线程执行,这时候通知中心会持有self,所以不会释放

结论:

所以为了避免通知因为线程阻塞,最好是主线程发通知,需要耗时操作的逻辑在接收到通知以后自己开线程处理。

参考:

  1. Notification Programming Topics

  2. Threading Programming Guide

  3. NSNotification的几点说明

  4. NSNotificationCenter is thread-safe NOT

  5. Observers and Thread Safety

  6. Notification与多线程

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容