简体   繁体   中英

Getting Parent of A View Controller Pushed on a UINavigationController stack in a UITabBarController with Multiple UINavigationControllers

So here's a problem I'm really having trouble with. I am using this code to retrieve the parent controller of a UIViewController that is pushed to the UINavigationController stack:

MyAppDelegate *delegate = [[UIApplicationDelegate sharedApplication] delegate];
UINavigationController *nav = delegate.navigationController;
MyParentViewController *parent = (MyParentViewController *)nav.topViewController;
parent.myProperty = @"propertyValue";

However, this seems to only work when you are working with an application with a single navigation controller. My structure is:

->UITabBarController
-->UINavigationController
--->MyYetAnotherParentViewController
-->UINavigationController
--->MyOtherParentViewController
-->UINavigationController
--->MyParentViewController

which means that I have 3 navigation controllers inside the tab bar controller.

I am currently in the third navigation controller and have pushed a view controller above MyParentViewController.

I am trying to pass data from the UIViewController I pushed to MyParentViewController using properties. How will I retrieve the parent of the UIViewController I pushed to the stack if I have this setup?

不确定这是否是您要查找的内容,但我认为它是 [nav viewControllers] 数组中最顶层的 ViewController。

Even if you are able to achieve this using this method, this does not align well with the MVC design pattern. Ideally, your child VC should call a method of your model class (which may be a singleton) & the model class should notify your parent VC. You can do something like-

//In your child VC 
[[MyModelClass sharedInstance] buttonClickedInChildVC:@"propertyValue"];

//In your Model class
[[NSNotificationCenter defaultCenter] postNotificationName:@"buttonClickedInChildVC" object:@"propertyValue"];

//In your Parent VC
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(buttonClickedInChildVC:) 
                                                 name:@"buttonClickedInChildVC"
                                               object:nil];

-(void)buttonClickedInChildVC:(NSNotification *) notification
{
    //do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM