如果我希望它在整个应用程序生命周期内都存在,是否需要手动删除观察者?

Do I need to remove observer manually if I want it to be there for the entire app life time?

我的 NSNotification Observer 不仅仅针对某个视图或视图控制器。我希望它仅在用户关闭应用程序时被删除。我将 "add observer" 放在 AppDelegate 中。我是否仍然需要在 deinit 中手动删除它,或者它会在应用程序关闭时自动删除?

当应用程序终止时,然后调用方法,即

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. 
}

您可以移除观察者:

或者您可以在此处删除观察者:

- (void)applicationDidEnterBackground:(UIApplication *)application
{

}

当应用程序进入后台时。

如果您想要某个视图控制器的通知,请将 add observer 添加到特定的 类 和 remove observer 中的 viewDidDisappear。 Ae看到你的情况,现在你已经在 app delegate 中添加了 add observer ,然后你可以根据你的要求在下面的方法中删除它。

- (void)applicationWillResignActive:(UIApplication *)application 
- (void)applicationDidEnterBackground:(UIApplication *)application
- (void)applicationWillTerminate:(UIApplication *)application

我认为,你应该在

中编写你的代码
 deinit{
   //remove observer here
}

在 Appdelegate 中添加以上方法 class.

希望对您有所帮助。谢谢

试试这个

你必须在 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];
}

希望对你有帮助。