Search code examples
iphoneobjective-cioscocoa-touchkey-value-observing

When to observe model data when using Storyboards


Let's assume I have an address book App. So from the address list I now push to a detail view like so:

  1. User taps on cell in the master list
  2. Segue showDetail is invoked
  3. In prepareForSegue: I set the model object contact of my ContactDetailViewController
  4. viewWillAppear I add an observer for self.contact
  5. So now when the contact object changes in the background, the detail view will automatically be updated.
  6. In viewWillDisappear I remove this observer (I guess it's clean because it is symetrical).

However, viewWillAppear: is called after I set the contact. So should I setup the KVO differently or simply call my updateView function in viewWillAppear which is a bit stupid because I want to get rid of those calls with KVO in the first place.


Solution

  • When you call addObserver:... you want to include the option NSKeyValueObservingOptionInitial. This will cause KVO to send the equivalent of a didChangeValueForKey: notification (i.e. an "Initial" notification) in the same call that adds the observation. This should cause your view to update at that time.