前幾天面試富途證券,被問到添加通知的相關問題,當時有幾個問題答錯了,在此總結。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: