关于NSNotificationCenter消息通信用法

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

 1 - (void)viewDidLoad
 2 {
 3     [super viewDidLoad];
 4     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someMethod:) name:kMyNotificationIdentifier object:nil];
 5 }
 6 
 7 - (void)dealloc
 8 {
 9     [[NSNotificationCenter defaultCenter] removeObserver:self];
10 }
11 
12 - (void)someMethod:(NSNotification *)note
13 {
14     // Message received
15 }

利用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];
}
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3447420.html