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

前端 未结 10 1493
萌比男神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:25

    The only way to do this is to set a flag when you add an observer.

    0 讨论(0)
  • 2020-12-04 07:26

    The whole point of the observer pattern is to allow an observed class to be "sealed" -- to not know or care whether it is being observed. You are explicitly trying to break this pattern.

    Why?

    The problem you are having is that you are assuming you are being observed when you aren't. This object did not start the observation. If you want your class to have control of this process, then you should consider using the notification center. That way your class has full control on when data can be observed. Hence, it doesn't care who is watching.

    0 讨论(0)
  • 2020-12-04 07:29

    The real question is why you don't know whether you're observing it or not.

    If you're doing this in the class of the object being observed, stop. Whatever's observing it expects to keep observing it. If you cut off the observer's notifications without its knowledge, expect things to break; more specifically, expect the observer's state to go stale as it doesn't receive updates from the formerly-observed object.

    If you're doing this in the observing object's class, simply remember which objects you're observing (or, if you only ever observe one object, whether you're observing it). This is assuming that the observation is dynamic and between two otherwise-unrelated objects; if the observer owns the observed, just add the observer after you create or retain the observed, and remove the observer before you release the observed.

    Adding and removing an object as an observer should usually happen in the observer's class, and never in the observed object's.

    0 讨论(0)
  • 2020-12-04 07:29

    [someObject observationInfo] return nil if there is no observer.

    if ([tableMessage observationInfo] == nil)
    {
       NSLog(@"add your observer");
    }
    else
    {
      NSLog(@"remove your observer");
    
    }
    
    0 讨论(0)
提交回复
热议问题