0

I add observer to an UITableView property.

[tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

As we all know, when UIViewController is popped -[UIViewController dealloc] method is called and -[UIViewController viewWillUnload] when it receives memory warning.

Should I remove observer in TWO places (ok, anyway I have to)? This is the code duplication at it's best. Or maybe I can call -[UIViewController viewWillUnload] in -[UIViewController dealloc] (as written in Three20 framework)? Is this approach good?

efpies
  • 3,625
  • 6
  • 34
  • 45
  • Refer [KVO and ARC how to removeObserver](http://stackoverflow.com/a/6960224/1106035) link Refer [Remove Observer issue in KVO in ios](http://stackoverflow.com/a/12601081/1106035) link also – Paresh Navadiya Oct 09 '12 at 12:13
  • This method is not called when `UIViewController` is popped. This is the question. – efpies Oct 09 '12 at 12:14
  • This answers the question "Should I remove observer?", not "How to not duplicate code when I add observer to one of `-[UIController view]` subviews?" – efpies Oct 09 '12 at 13:42

1 Answers1

1

You should only remove the observer in dealloc. If you do it in viewWillUnload also, you could potentially remove the observer twice, which will crash your app. However, adding an observer twice isn't a problem. Even if you nil tableView in viewDidUnload, the observer can continue to exist, it just won't do anything.

David
  • 1,152
  • 8
  • 13
  • I can't do this only in `-[UIViewController dealloc]` because `UITableView` to which properties I add observer will be destroyed on `-[UIViewController didReceiveMemoryWarning]`: it calls `-[UIViewController viewWillUnload]` but not call `-[UIViewController dealloc]`. And the last doesn't call `-[UIViewController viewWillUnload]`. – efpies Oct 10 '12 at 16:22