Keeping MasterViewController and DetailViewController in sync

不羁岁月 提交于 2019-12-23 01:53:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!