简体   繁体   English

iOS应用程序崩溃,因为KVO观察者不再观察

[英]iOS App crashes because KVO observer is not observing anymore

Is there a way to know if there are objects listening on a keypath for a view controller. 有没有办法知道是否有对象在视图控制器的键路径上侦听。 For example, I have in my viewcontroller 例如,我的视图控制器中有

[tabBarController addObserver:self
     forKeyPath:@"selectedViewController"
     options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
     context:&PrivateKVOContext
]; (edited)

And I want to know if my tabbarcontroller can know if my viewcontroller is listening on that keypath 我想知道我的tabbarcontroller是否可以知道我的viewcontroller是否在该键路径上进行监听

The reason is because my app crashes because the tab bar controller still thinks my view controller is listening on that key path even though my view controller has been deallocated 原因是因为我的应用程序崩溃是因为选项卡栏控制器仍然认为我的视图控制器正在侦听该关键路径,即使我的视图控制器已被释放

And in the dealloc method of my viewcontroller, I put [tabBarController removeObserver:self forKeyPath:@"selectedViewController”]; to remove itself as an observer 在我的viewcontroller的dealloc方法中,我将[tabBarController removeObserver:self forKeyPath:@"selectedViewController”];为观察者

Sadly not. 可惜不是。 There's no way to check which objects are currently observing other objects. 无法检查当前哪些对象正在观察其他对象。

As such, it's generally recommended that you place removeObserver: in the complementing method to the one where you placed addObserver: so they'll be reliably called an equal number of times. 因此,通常建议您在放置removeObserver:的方法的补充方法中放置addObserver:以便可靠地将它们调用相同的次数。

In this case, since you're putting it in dealloc, which is called at the end of the view controller's lifecycle, you should put addObserver: in your init method, which will be called at the very start. 在这种情况下,由于您将其放入dealloc(在视图控制器生命周期结束时调用),因此应将addObserver:放在init方法中,该方法将在开始时调用。

It depends on if the observer really in use, in your code , try this: 这取决于在代码中是否真正使用了观察者,请尝试以下操作:

- (void)dealloc {

    @try {
        [[NSNotificationCenter defaultCenter] removeObserver:Notification_Location_Ready];
    } @catch (NSException *exception) {

    } @finally {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM