#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(action:) name:@"notificationName" object:nil];
}
// 主线程发送通知
- (IBAction)actionA:(UIButton *)sender {
// 发送通知
NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
[center postNotificationName:@"notificationName" object:self userInfo:@{@"key":@"notificationName"}];
NSLog(@"发送通知线程 = %@",[NSThread currentThread]);
}
// 子线程发送通知
- (IBAction)actionB:(UIButton *)sender {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 发送通知
NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
[center postNotificationName:@"notificationName" object:self userInfo:@{@"key":@"notificationName"}];
NSLog(@"发送通知线程 = %@",[NSThread currentThread]);
});
}
// 接收通知相应的方法
- (void)action:(NSNotification *)notice {
NSLog(@"接收通知线程 = %@",[NSThread currentThread]);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"主线程更新 UI %@", [NSThread currentThread]);
});
}
// 移除通知
- (void)dealloc {
// 移除当前所有通知
NSLog(@"移除了所有的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
打印结果:
当在主线程发送通知时:
发送通知线程 = <NSThread: 0x600002c74780>{number = 1, name = main}
接收通知线程 = <NSThread: 0x600002c74780>{number = 1, name = main}
当在子线程发送通知时:
发送通知线程 = <NSThread: 0x600002c57d40>{number = 5, name = (null)}
接收通知线程 = <NSThread: 0x600002c57d40>{number = 5, name = (null)}
结论:
通知在哪个线程发送,接收就在那个线程。
网友评论