How can i tell if an object has a key value observer attached

前端 未结 10 1510
萌比男神i
萌比男神i 2020-12-04 06:51

if you tell an objective c object to removeObservers: for a key path and that key path has not been registered, it cracks the sads. like -

\'Cannot remove an observe

10条回答
  •  臣服心动
    2020-12-04 07:07

    In my opinion - this works similar to retainCount mechanism. You can't be sure that at the current moment you have your observer. Even if you check: self.observationInfo - you can't know for sure that you will have/won't have observers in future.

    Like retainCount. Maybe the observationInfo method is not exactly that kind of useless, but I only use it in debug purposes.

    So as a result - you just have to do it like in memory management. If you added an observer - just remove it when you don't need it. Like using viewWillAppear/viewWillDisappear etc. methods. E.g:

    -(void) viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
        [self addObserver:nil forKeyPath:@"" options:NSKeyValueObservingOptionNew context:nil];
    }
    
    -(void) viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
        [self removeObserver:nil forKeyPath:@""];
    }
    

    And it you need some specific checks - implement your own class that handles an array of observers and use it for your checks.

提交回复
热议问题