title: When should I call removeObserver:forKeyPath from within a closing ViewController class that is observing a persistant Model class?
body: <p>I have a <code>ViewController</code> class that has a property that is the model which I want to observe as properties on the model change.  Within my model object I have a property that is periodically updated in the background of my application.  As it updates, I need to execute code within my <code>ViewController</code>.</p>
  
  <p>To do this, I create an observer on my model from within my <code>ViewController</code> <code>viewDidLoad</code> method.</p>
  
  <pre><code>[ModelObject addObserver:self 
                forKeyPath:@"State" 
                   options:NSKeyValueObservingOptionNew 
                   context:nil];
  </code></pre>
  
  <p>As you can see, this is nothing special and the observation method behaves as it should so long as I leave the view displayed on my screen.  If I remove the above view from the parent view, I get an <code>EXC_BAD_ACCESS</code> error message when my <code>ModelObject</code> instance <code>Mode</code> property changes.  Specifically, my app crashes at the line that is updating the <code>Mode</code> property and I receive the mostly useless <code>EXC_BAD_ACCESS</code> on the following line of code within the ModelObject instance.</p>
  
  <pre><code>//This is located in a method that periodically toggles the value of "State"
  [self setState: 2];
  </code></pre>
  
  <p>I would assume the solution to this problem is to call <code>[ModelObject removeObserver: self forKeyPath:@"State"]</code> from somewhere within my <code>ViewController</code> when it is removed from it's parent subview array.  However, I have added that line of code within my <code>viewDidUnload</code> method but I've found the the <code>viewDidUnload</code> method isn't being called.  I'm not sure if that is the right place, but it needs to go some where.</p>
  
  <p>What might I be doing incorrectly?  I know the problem is KVO related because if I remove the observation, the application works without any problem.  My model instance can toggle this value as much as it wants and my application never crashes.  What should I do to be sure that my observer is removed correctly when the observing view is being removed from it's parent's subview array?</p>