我的NSNotification Observer不僅僅適用於特定的視圖或視圖控制器。我希望只有在用戶關閉應用時才能將其刪除。我把「添加觀察者」放在AppDelegate中。我是否仍然需要手動刪除它,或者在應用程序關閉時自動刪除它?我是否需要手動刪除觀察者,如果我希望它在整個應用程序的生命週期中都在那裏?
0
A
回答
2
如果您想要某個視圖控制器的通知,請將add observer
添加到該特定的類別中,並將remove observer
添加到viewDidDisappear
中。 Ae見過你的案例,現在你已經在app delegate
中加入了add observer
,那麼你可以根據你的要求在下面的方法中刪除它。
- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application
- (void)applicationWillTerminate:(UIApplication *)application
1
當應用程序是終止再一個方法調用,即
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate.
}
您可以刪除觀察者:
,或者你CAL去除這裏的觀察者:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
當應用進來背景。
1
我想,你應該寫你的代碼
deinit{
//remove observer here
}
添加上述AppDelegate類方法。
希望這會幫助你。由於
1
試試這個
你必須在的addObserver didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(<#your selector#>)
name:@"TestNotification"
object:nil];
return YES;
}
然後在applicationWillTerminate
刪除觀察者。你不需要在其他方法中刪除觀察者,因爲很多時候應用程序會去後臺,並且不會一直調用didFinishLaunchingWithOptions
。所以你必須在applicationWillTerminate
中刪除。
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
希望它可以幫助你。
相關問題
- 1. 我需要與Android應用程序生命週期的協調
- 2. 我希望突變觀察者來監聽它的目標節點本身是否在javascript中被移除
- 3. 我們是否應該在dealloc中爲UIView移除觀察者?
- 4. 何時需要刪除觀察者
- 5. 如果在AppDelegate中添加通知的觀察者,是否需要打擾刪除它?
- 6. 在應用程序生命週期中何處刪除委託?
- 7. 我需要從NSNotificationCenter中刪除觀察者一次,還是一次添加觀察者?
- 8. 我應該在applicationWillTerminate中刪除觀察者嗎?
- 9. 如何測試hibernate生命週期觀察者?
- 10. 我是否需要在調用async_write時關心套接字的生命週期?
- 11. 當我的對象被破壞時,我需要刪除觀察者嗎?
- 12. 觀察者模式是否適用於主題和觀察者需要位於單獨的程序集中?
- 13. 我需要puting介紹動畫視頻,我的應用程序幫助,我希望它午飯應用
- 14. 我是否需要手動刪除或管理這個unique_ptr
- 15. 在使用統一的asp.net MVC2中,我的程序是否需要管理容器的生命週期?
- 16. 如何在ViewController關閉時在Monotouch iOS應用程序中刪除觀察者
- 17. FMDB:在ios應用程序的整個生命週期中,它是否很好的開放數據庫?
- 18. 如果我不從nsnotification中心刪除觀察者,會發生什麼情況?
- 19. 在iCloud應用程序中進行編輯時,是否需要將viewController作爲觀察者移除?
- 20. 我應該在哪裏刪除通知觀察員?
- 21. 如何刪除觀察者
- 22. 在所有的應用程序生活中,Firebase觀察者
- 23. 如何測試我的android應用程序的生命週期?
- 24. 不再需要刪除可可中的通知觀察者?
- 25. 在UICollectionViewCell中添加/刪除觀察者
- 26. 在觀察者中刪除訂閱
- 27. NSNotificationCenter:在Swift中刪除觀察者
- 28. 我是否需要觀察每個創建的NSManagedObjectContext的NSManagedObjectContextDidSaveNotification?
- 29. 我希望我的MVC應用程序是一個網站
- 30. Android - 如何在整個應用程序生命週期中使用ORMLite dbhelper
你是否在'didFinishLaunchingWithOptions'中添加了觀察者? – Vvk
@Vvk是的,我在那裏添加它 – den330
你必須在AppDelegate的'applicationWillTerminate'方法中刪除觀察者 – Vvk