- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block NS_AVAILABLE(10_6, 4_0);
看得出来,这个是苹果在iOS10.6中新加的方法
与之前的用法不同的是,它并不指定observer,而是通过block处理相关逻辑,同时返回一个observer,用于在界面销毁时进行移除;
话不多说,我们来看看用法:
正常使用:
{
id newMessageObserver;//定义全局observer
}
//接收observer
newMessageObserver = [[NSNotificationCenter defaultCenter] addObserverForName:TCM_NewMessage_Notification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
//Do something
}];
- (void)dealloc{
//remove observer
[[NSNotificationCenter defaultCenter] removeObserver:newMessageObserver];
}
只使用一次:
NSNotificationCenter *__weak center = [NSNotificationCenter defaultCenter];
id __block newMessageObserver = [center addObserverForName:TCM_NewMessage_Notification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
//Do something
//remove observer
[center removeObserver:newMessageObserver];
}];