2016-07-11 18 views
0

我的NSNotification Observer不僅僅適用於特定的視圖或視圖控制器。我希望只有在用戶關閉應用時才能將其刪除。我把「添加觀察者」放在AppDelegate中。我是否仍然需要手動刪除它,或者在應用程序關閉時自動刪除它?我是否需要手動刪除觀察者,如果我希望它在整個應用程序的生命週期中都在那裏?

+0

你是否在'didFinishLaunchingWithOptions'中添加了觀察者? – Vvk

+0

@Vvk是的,我在那裏添加它 – den330

+0

你必須在AppDelegate的'applicationWillTerminate'方法中刪除觀察者 – Vvk

回答

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]; 
} 

希望它可以幫助你。

相關問題