通知与线程

代码:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    /// 添加通知中心观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"MyNotification" object:nil];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 创建一个子线程用于发布通知
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(postNotification) object:nil];
    [thread start];
}

// 发布通知
- (void)postNotification {
    NSLog(@"%@", [NSThread currentThread]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:nil];
}

// 接受通知
- (void)receiveNotification:(NSNotification *)notification {
    NSLog(@"%@", [NSThread currentThread]);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
}

@end

输出:

<NSThread: 0x7f8f14083af0>{number = 2, name = (null)}
<NSThread: 0x7f8f14083af0>{number = 2, name = (null)}

结论:

在哪一个线程发布通知,就会在那一个线程调用对应的通知的处理方法。

原文地址:https://www.cnblogs.com/xwoder/p/4586774.html