美文网首页
iOS NotificationCenter 总结

iOS NotificationCenter 总结

作者: yxibng | 来源:发表于2022-11-19 22:21 被阅读0次

    参考文档: 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
    
    

    相关文章

      网友评论

          本文标题:iOS NotificationCenter 总结

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