问题
I am writing a simple iPad appication using Xcode 4 and iOS5.
I am using a UISplitViewController to manage a master and detail view. Everything is working fine going from master to detail. I can select an item from the list and through the delegate it updates the detail view.
I want to be able to delete an item using a button on the detail view. This is very simple to do on the detail view. However, I cannot seem to figure out how to change the master view to reflect the fact that an item has been deleted.
Basically the delegate pattern seems to only go one way; from master to detail and not from detail to master. Is there a way to pass messages from the detail to the master?
回答1:
You can do it with NSNotifications.
#define ReloadMasterTableNotification @"ReloadMasterTableNotification"
In your viewDidLoad of MasterViewController:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMasterTable:) name:ReloadMasterTableNotification object:_detailViewController];
in dealloc of MasterViewController if you're using ARC:
[[NSNotificationCenter defaultCenter] removeObserver:self name:ReloadMasterTableNotification object:nil];
When you want to make your update in the detailViewController to notify the MasterViewController:
- (IBAction)onButtonPress {
NSIndexPath *path = [NSIndexPath indexPathForRow:indexToUpdate inSection:0];
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:path, @"IndexPath", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:ReloadMasterTableNotification object:self userInfo:dict];
}
- (void)reloadMasterTable:(NSNotification *)notification {
NSDictionary *dict = [notification userInfo];
NSIndexPath *path = [dict objectForKey:@"IndexPath"];
// update MasterViewController here
}
Hope that helps!
来源:https://stackoverflow.com/questions/9316595/keeping-masterviewcontroller-and-detailviewcontroller-in-sync