Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

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

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 error which seems to occur before my dealloc method gets called, according to my debug prints.

An instance 0x583870 of class TekkPoint is being deallocated while key value observers are still registered with it. Observation info is being leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info: ( Context: 0x0, Property: 0x536400> Context: 0x0, Property: 0x55aba0> )

Is there a particular way I should remove observers? Or perhaps a particular place that I should be removing them?

According to this question I am doing things right, but why would I get this error message?

Here is my dealloc routine:

- (void)dealloc {
  // Remove all observers.
  for (NSString *path in [TekkPoint observedPaths]) {
    [self removeObserver:[option_ tChart]
          forKeyPath:path];

  }

  [description_ release];
  [weight_ release];
  [super dealloc];
}

One thing to note that might be strange about my implementation is that I am adding and removing observers from the observee, could this cause my problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...