Curt Rand
Curt Rand

Reputation: 1045

iOS: Best practice to know when two view controllers are loaded after navigation push

I have an iOS app that displays multiple screens and has different root controller for both iPhone and iPad. Here is a simplified example code to show what is going on.

if (iPad) {
    self.sideMenuController = [LGSideMenuController sideMenuControllerWithRootViewController:viewControllerA
                                                        leftViewController:viewControllerB
                                                        rightViewController:nil];   
} else {
    self.sideMenuController = [LGSideMenuController sideMenuControllerWithRootViewController:viewControllerB
                                                        leftViewController:viewControllerA
                                                        rightViewController:nil];   
  }

 [self.navigationController pushViewController:self.sideMenuController animated:NO];

I need to be able to tell when both controllers (ViewControllerA and ViewControllerB) is loaded.

I've implemented the following delegate

   - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
        if (self.viewControllerA.viewIfLoaded.window != nil && self.viewControllerB.viewIfLoaded.window != nil) {
           // do stuff after both controllers have been loaded and it is current view.
        }
    }

The delegate solution works, but not sure if it is best practice. I check if viewControllerA and viewControllerB is not nil and current view controllers because I push other controllers in the navigation controller and don't want to do anything if that happens.

Upvotes: 0

Views: 67

Answers (3)

tedrothrock
tedrothrock

Reputation: 368

Assuming that the root view controller always loads first, you could perform work in the viewDidLoad method of the non-root view controller, which you could determine by referencing the device type.

Upvotes: 0

Martin Prusa
Martin Prusa

Reputation: 211

You can have some BaseClass that both viewControllers inherit from (ViewControllerA and ViewControllerB) and in that BaseClass, you can use viewDidLoad: method to run whatever code you want.

Upvotes: 0

matt
matt

Reputation: 535945

It seems fragile. You're making a lot of assumptions and not (as far as I can tell) asking the navigation controller the question you really want to know the answer to. That question would be (as far as I can tell):

  • Is the view controller that just got pushed one of VCA and VCB?
  • Is the other of that pair already the navigation controller's child?

Upvotes: 1

Related Questions