关于NSNotificationCenter消息通信用法

时间:2023-03-09 16:51:43
关于NSNotificationCenter消息通信用法

NSNotificationCenter主要用于广播消息到多个监听着,其传统用法

 - (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someMethod:) name:kMyNotificationIdentifier object:nil];
} - (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
} - (void)someMethod:(NSNotification *)note
{
// Message received
}

利用Blocks操作

@implementation MyViewController
{
id _notificationObserver;
} // ... - (void)viewDidLoad
{
[super viewDidLoad];
_notificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kMyNotificationIdentifier object:nil queue:nil usingBlock:^(NSNotification *note) {
// message received
}];
} // dealloc, or potentially a method popping this view from the stack
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:_notificationObserver];
}