iOS - NSNotificationCenter

284 阅读1分钟

1、主线程监听,子线程发通知

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"1");
    dispatch_queue_t queue = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        NSLog(@"serial %@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil];
    });
    NSLog(@"2");
}

- (void)receive {
    NSLog(@"receive %@",[NSThread currentThread]);
}

@end

在主线程监听,子线程发通知,会在子线程接收到通知。

截屏2021-06-04 下午3.52.54.png

2、子线程监听,子线程发通知

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"global%@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil];
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"1");
    dispatch_queue_t queue = dispatch_queue_create("serial", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"serial %@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil];
    });
    NSLog(@"2");
}

- (void)receive {
    NSLog(@"receive %@",[NSThread currentThread]);
}

@end

子线程监听,子线程发通知,会在发通知的线程里接收到消息

截屏2021-06-04 下午3.55.10.png

3、子线程监听,主线程发通知

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"global%@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receive) name:@"testNoti" object:nil];
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"1");
    NSLog(@"serial %@",[NSThread currentThread]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"testNoti" object:nil];
    NSLog(@"2");
}

- (void)receive {
    NSLog(@"receive %@",[NSThread currentThread]);
}

@end

子线程监听,主线程发通知,会在主线程接收到消息.

截屏2021-06-04 下午3.57.22.png

总结:接收通知和发送通知时所在线程一致,和监听时所在线程无关。