前几天面试富途证券,被问到添加通知的相关问题,当时有几个问题答错了,在此总结。html
//一、注册多个通知 for (int i =0; i<3; i++) { [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifycationMehod:) name:@"testNotifycation" object:nil]; } //二、传递通知 [[NSNotificationCenter defaultCenter]postNotificationName:@"testNotifycation" object:nil];
输出结果面试
2016-12-01 17:06:23.868 NotifycationDemo[28703:10079806] receive notifycation object (null) 2016-12-01 17:06:23.868 NotifycationDemo[28703:10079806] receive notifycation object (null) 2016-12-01 17:06:23.869 NotifycationDemo[28703:10079806] receive notifycation object (null)
- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; //注册通知 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifycationMehod:) name:@"testNotifycation" object:nil]; } - (void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; //没有remove通知 }
2016-12-01 17:24:13.722 NotifycationDemo[28820:10087367] receive notifycation object (null)
app
2016-12-01 17:24:13.723 NotifycationDemo[28820:10087367] receive notifycation object (null)
async
4.移除一个name没有add的通知,不会崩溃[[NSNotificationCenter defaultCenter]removeObserver:self name:@"unknownName" object:nil];
@implementation NotifyTestClass - (void)registerMyNotifycation{ [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifycationMehod) name:@"testNotifycation" object:nil]; } - (void)notifycationMehod{ NSLog(@"NotifyTestClass receive notify"); } - (void)dealloc{ NSLog(@"NotifyTestClass dealloc"); } @end //局部变量 马上释放 NotifyTestClass *nt = [[NotifyTestClass alloc]init]; [nt registerMyNotifycation]; //发送通知 [[NSNotificationCenter defaultCenter]postNotificationName:@"testNotifycation" object:nil];
输出结果post
苹果官网文档有说明,iOS 9.0以后NSNotificationCenter不会对一个dealloc的观察者发送消息因此这样就不会崩溃了。果然我换了一个8.1的手机测试,程序崩溃了,原来是作了优化。2016-12-01 19:29:15.039 NotifycationDemo[29035:10119206] NotifyTestClass dealloc
@implementation TwoViewController - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifycationMehod) name:@"testNotifycation" object:nil]; // Do any additional setup after loading the view from its nib. } - (void)notifycationMehod{ NSLog(@"TwoViewController receive notify"); } - (void)dealloc{ NSLog(@"TwoViewController dealloc"); } @end
输出结果测试
2016-12-02 16:36:42.175 NotifycationDemo[31359:10305477] TwoViewController dealloc 2016-12-02 16:36:42.176 NotifycationDemo[31359:10305477] removeObserver = <TwoViewController: 0x7fa42381d720>
所以咱们若是要接受一些通知更新UI的时候,咱们须要回到主线程来处理。
dispatch_async(dispatch_get_main_queue(), ^{ //do your UI });
Reference: