我的NSNotification Observer 不仅适用于某个视图或视图控制器。我希望仅在用户关闭应用程序时将其删除。我将"添加观察者"放在AppDelegate中。我是否仍需要在 deinit 中手动删除它,或者它在应用程序关闭时会自动删除?
如果您想通知某些视图控制器,请将add observer
添加到该特定类并在viewDidDisappear
中remove observer
。 Ae 看到了您的情况,现在您已在 app delegate
中添加了add observer
,然后您可以根据需要在以下方法中删除它。
- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application
- (void)applicationWillTerminate:(UIApplication *)application
当应用程序终止时,然后调用方法,即
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate.
}
您可以移除观察程序:
或者您在此处删除观察者:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
当应用程序在后台出现时。
,你应该用
deinit{
//remove observer here
}
在 Appdelegate 类中添加上述方法。
希望这对您有所帮助。谢谢
试试这个
您必须在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];
}
希望对您有所帮助。