iOS NotificationCenter 总结

参考文档: Notification Programming Topics

NSNotificationCenter

  1. 用于单个进程内的通知发送
  2. postNotificationName:object:postNotificationName:object:userInfo: 的调用为同步方式,该方法会等待通知被发送和处理后返回。
  3. 通知注册的handler是在发送通知的线程中被调用,主线程注册了通知,子线程发送了通知,通知的处理就是在子线程中。如果想在主线程中同步处理该通知,可以通过mach port, 将通知转发给主线程。

NSNotificationQueue

NSNotificationQueue objects, or simply, notification queues, act as buffers for notification centers (instances of NSNotificationCenter). The NSNotificationQueue class contributes two important features to the Foundation Kit’s notification mechanism: the coalescing of notifications and asynchronous posting.

Using the NSNotificationCenter’s postNotification: method and its variants, you can post a notification to a notification center. However, the invocation of the method is synchronous: before the posting object can resume its thread of execution, it must wait until the notification center dispatches the notification to all observers and returns. A notification queue, on the other hand, maintains notifications (instances of NSNotification) generally in a First In First Out (FIFO) order. When a notification rises to the front of the queue, the queue posts it to the notification center, which in turn dispatches the notification to all objects registered as observers.

Every thread has a default notification queue, which is associated with the default notification center for the process. You can create your own notification queues and have multiple queues per center and thread.

  1. 每条线程都有一个默认的通知队列, 队列的任务先入先出
  2. 通过通知队列可以异步发送通知,通过 NSNotificationCenter 只能同步发送通知
  3. 通知队列允许通知折叠,多条通知折叠为一条发送,可以指定折叠的策略, 例如: 按通知名字折叠
  4. 需要关联runloop,指定要运行的runloop mode
  5. 因为指定了runloop,指定通知发送的时机
    • NSPostASAP
    • NSPostWhenIdle
    • NSPostNow

调用:

NSNotificationQueue *queue = [NSNotificationQueue defaultQueue];
[queue enqueueNotification ...]

NSDistributedNotificationCenter

Each process has a default distributed notification center that you access with the NSDistributedNotificationCenter +defaultCenter class method. This distributed notification center handles notifications that can be sent between processes on a single machine. For communication between processes on different machines, use distributed objects (see Distributed Objects Programming Topics).

Posting a distributed notification is an expensive operation. The notification gets sent to a systemwide server that then distributes it to all the processes that have objects registered for distributed notifications. The latency between posting the notification and the notification’s arrival in another process is unbounded. In fact, if too many notifications are being posted and the server’s queue fills up, notifications can be dropped.

Distributed notifications are delivered via a process’s run loop. A process must be running a run loop in one of the “common” modes, such as NSDefaultRunLoopMode, to receive a distributed notification. If the receiving process is multithreaded, do not depend on the notification arriving on the main thread. The notification is usually delivered to the main thread’s run loop, but other threads could also receive the notification.

Whereas a regular notification center allows any object to be observed, a distributed notification center is restricted to observing a string object. Because the posting object and the observer may be in different processes, notifications cannot contain pointers to arbitrary objects. Therefore, a distributed notification center requires notifications to use a string as the notification object. Notification matching is done based on this string, rather than an object pointer.

  1. 提供跨进程通知的能力, iOS用不了, iOS需要使用CFNotificationCenterGetDarwinNotifyCenter
  2. 当通知队列满的时候,后面到来的通知会被丢弃
  3. 需要关联runloop, 一般的通知会发布到主线程中,但是子线程也可以收到通知
  4. 通知的object信息,只能是string, 因为跨进程通知,传递对象指针没有意义
  5. 可以定制策略和发送时机
- (void)addObserver:(id)observer selector:(SEL)selector name:(NSNotificationName)name object:(NSString *)object suspensionBehavior:(NSNotificationSuspensionBehavior)suspensionBehavior;

- (void)postNotificationName:(NSNotificationName)name object:(NSString *)object userInfo:(NSDictionary *)userInfo options:(NSDistributedNotificationOptions)options;

CFNotificationCenterGetDarwinNotifyCenter

支持 iOS、macOS, 提供跨进程通知的能力

swift 中如何使用, 参考: Swift - 正确使用CFNotificationCenterAddObserver 回调

//发送通知
sendNotificationForMessageWithIdentifier(identifier: "broadcastStarted")
func sendNotificationForMessageWithIdentifier(identifier : String) {
    let center : CFNotificationCenter = CFNotificationCenterGetDarwinNotifyCenter()
    let identifierRef : CFNotificationName = CFNotificationName(identifier as CFString)
    CFNotificationCenterPostNotification(center, identifierRef, nil, nil, true)
}

///通知回调
func callback(_ name : String) {
    print("received notification: \(name)")
}

///通知注册
func registerObserver() {
    let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer, { (_, observer, name, _, _) -> Void in
        if let observer = observer, let name = name {
            // Extract pointer to `self` from void pointer:
            let mySelf = Unmanaged<OTCAppealVC>.fromOpaque(observer).takeUnretainedValue()
            // Call instance method:
            mySelf.callback(name.rawValue as String)
        }
    }, "broadcastFinished" as CFString, nil,.deliverImmediately)
}

//通知移除
deinit {
    let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())
    let cfName: CFNotificationName = CFNotificationName("broadcastFinished" as CFString)
    CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer, cfName, nil)
}

NSMachPort 转发通知到特定线程

例如在主线程监听,在子线程中发送通知,希望通知仍然在主线程中处理

#import "ViewController.h"

@interface ViewController ()<NSMachPortDelegate>
@property(nonatomic, strong) NSMutableArray *notifications;
@property (nonatomic, strong) NSThread *notificationThread;
@property (nonatomic, strong) NSLock *notificationLock;
@property (nonatomic, strong) NSMachPort *notificationPort;
@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.notifications = [[NSMutableArray alloc] init];
    self.notificationThread = [NSThread mainThread];
    self.notificationLock = [[NSLock alloc] init];
    self.notificationPort = [[NSMachPort alloc] init];
    
    [self.notificationPort setDelegate:self];
    [[NSRunLoop currentRunLoop] addPort:self.notificationPort
            forMode:NSRunLoopCommonModes];
    
    [[NSNotificationCenter defaultCenter]
            addObserver:self
            selector:@selector(processNotification:)
            name:@"NotificationName"
            object:nil];
    
    
    for (int i = 0; i< 10; i++) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:self];
        });
    }
}

- (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] != self.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];

        NSLog(@"notification receive in thread: %@", [NSThread currentThread]);
    }
    else {
        // Process the notification here;
        NSLog(@"notification handle in thread: %@", [NSThread currentThread]);
    }
}

@end

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

推荐阅读更多精彩内容