Communication from child UIViewController to parent UIViewController
cocoa-touch, iphone, model-view-controller, uiviewcontroller
Solution
When communication to parent objects you have a few design patterns to choose from. Delegation and Notification are both good choices.
The big idea here is communication with loose coupling. Notifications use a Singleton to handle communication while Delegation uses weak references to parent objects. (Check out Cocoa With Love: retain cycles)
If you go with delegation, you can create an informal protocol for your ViewControllerA which MainViewController must conform to.
You may call it the ViewControllerADelegate protocol:
@protocol ViewControllerADelegate
@optional
- (void)bringSubViewControllerToFront:(UIViewController*)aController;
@end
Or ViewControllerA can post a notification:
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyFunkyViewSwitcherooNotification" object:self];
And MainViewController should be listenting if it wants to know:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(swapThoseViews:) name:@"MyFunkyViewSwitcherooNotification" object:nil];
Problem
I haven't figured out that yet: I have a mainViewController that switches two views, viewControllerA and ViewControllerB. The way I switch the view is by having a UIButton (mainButton) in the mainViewController, and clicking on it switches viewControllerA <--> ViewControllerB. Now here is my problem. My ViewControllerA has a UIButton (ButtonA). And I want that by clicking on it, it tells the mainViewController to switch to the other view (viewControllerB) In other words, the child view (viewControllerA) should send a message to the mainViewController(its parent view) that it wants to fire a method that belongs to the main view, not to itself (viewA). How could I achieve that please?