When should I remove observers? Error about deallocating objects before removing observers

后端 未结 4 506
清歌不尽
清歌不尽 2020-12-13 02:18

I am trying to use key-value observing in one of my classes. I register the observers in the init method and remove/deregister them in the dealloc, but I get the following e

相关标签:
4条回答
  • 2020-12-13 02:45

    Ah. You're observing a TekkPoint object from a SomethingElse object, and the SomethingElse object is the one adding and removing the observers, correct? (That's the normal way things are done; I'm just trying to clarify.)

    It looks like your TekkPoint object is being deallocated while the SomethingElse that's observing it is still around. The SomethingElse dealloc method isn't called because it's the TekkPoint that's being deallocated, not the SomethingElse.

    If you're planning on observing an object which may disappear before the observer disappears, then you need some way of notifying the observers that they should remove their observers. Your TekkPoint could have an alive property which would also be observed by the SomethingElse, and when it gets set to NO then everyone observing the TekkPoint would remove themself as an observer.

    0 讨论(0)
  • 2020-12-13 02:56

    why would you call

    [super dealloc]
    

    From apple documentation on dealloc

    In an implementation of dealloc, do not invoke the superclass’s implementation
    
    0 讨论(0)
  • 2020-12-13 03:02

    The normal code looks something like this:

    - (void) dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [super dealloc];
    }
    

    Double check your signature of your dealloc method (Objective C is very unforgiving and will never warn you when you mess up the name of a method). For example, if your method name was "dealoc" (with one l), your dealloc would never be called.

    Otherwise, edit your question to include your dealloc reoutine.

    0 讨论(0)
  • 2020-12-13 03:03

    Are you calling [super dealloc] before you remove your observers? Calling super's dealloc too early could lead to an error like this.

    0 讨论(0)
提交回复
热议问题