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];
}