Datasheet
758
Adding Some Code to Actually Add Some Functionality
Listing 1-4: viewWillDisappear:
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self cleanUpUndoManager];
// Save the context.
if (trip.managedObjectContext.hasChanges) {
NSError *error = nil;
if (![trip.managedObjectContext save:&error]) {
/*Replace this implementation with code to handle the
error appropriately. */
NSLog(@”Unresolved error %@, %@”, error,
[error userInfo]);
abort();
}
}
[trip loadHotels];
[trip.mapController refreshAnnotations];
[self resignFirstResponder];
}
This worked fine when the HotelController was the “last stop” in the
chain. That is, after you added the hotel, the only place to go was back to
the previous view controller, and if you were doing that, it meant you were
done with adding a hotel, and in viewWillDisapper: you could do what
you needed to based on the last user action.
When you added the AddHotelController, all this changed. The view-
WillDisappear: message is now also sent when you’re moving from the
HotelController to the AddHotelController, and at that point you
certainly aren’t ready to do much of anything.
Having a modification essentially gum up the works of what was laid down
before is not an uncommon occurrence during development — in fact, it’s
highly likely. (The general guideline is to count on writing any application
twice.) What you did (just to demonstrate to yourself, of course) is evidence
that something that works during a phase of development may not necessar-
ily be the best long-term solution. In reality, very few projects ever go from A
to B to . . . directly.
Fortunately, enhancing your code to handle this situation is easy.
All you have to do is save the new Hotel and refresh the annotations
after the user has returned from the AddHotelController and entered
the necessary data. To do that, you’ll simply add state information to the
HotelController — it needs to know whether it’s still in the middle of
adding a hotel when the view disappears, or not. If it’s in the middle of
adding it, don’t do anything. If it’s not, just do what you were doing before.
41_542934-bk07ch01.indd 75841_542934-bk07ch01.indd 758 3/23/10 11:01 PM3/23/10 11:01 PM