- 寫在ViewController中的注冊通知,在頁面pop后會自動在通知中心移除自己;寫在其他對象中的注冊通知,釋放后不會自動移除自己,這時候會引起崩潰。
- Viewcontroller正確的寫法應該是在willappear添加觀察,在willdisappear移除自己。
- 發送通知的線程可能和接受通知的線程可能不是同一個線程,在接受通知時,需要單獨處理。(NSNotificationCenter消息的接受線程是基于發送消息的線程的。也就是同步的,而有時候UI必須在主線程處理,不然會不響應,所以要針對處理)
eg.
//接受消息通知的回調
- (void)test
{
if ([[NSThread currentThread] isMainThread]) {
NSLog(@"main");
} else {
NSLog(@"not main");
}
dispatch_async(dispatch_get_main_queue(), ^{
//do your UI
});
}
//發送消息的線程
- (void)sendNotification
{
dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(defaultQueue, ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
});
}