0

is it possible to access a ViewController's methods from the appDelegate, like it is possible inverse with the following code:?

AppDelegate *ad = (AppDelegate *) [[UIApplication sharedApplication] delegate];

When I try

ViewController *vc = (ViewController *) [[UIApplication sharedApplication] delegate];

I get an error...

Thanks!

Pfitz
  • 7,336
  • 4
  • 38
  • 51
Linus
  • 4,643
  • 8
  • 49
  • 74
  • 1
    You're getting an error because you're calling something a `ViewController` that's obviously **not** a `ViewController`. (I say 'obviously' because it can't be one if it's already an `AppDelegate`.) You can do something like what you want but the code depends on how the view controller is being created. – Phillip Mills Jun 27 '12 at 11:44

2 Answers2

2

In your AppDelegate, assuming viewController is your rootViewController, you can get a list of all view controllers on the stack by with:

NSLog(@"List of current active view controllers:%@", self.viewController.navController.viewControllers);

To access a specific view controller in the viewControllers:

[[self.viewController.navController.viewControllers objectAtIndex:i] someMethodOfThatViewController]; 
user523234
  • 14,323
  • 10
  • 62
  • 102
1
ViewController *vc = (ViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;

or if your delegate have properties

YourAppDelegate *ad = (YourAppDelegate*)[UIApplication sharedApplication].delegate;
ViewController *vc = ad.yourViewControllerProperty;
Denis Kulygin
  • 323
  • 1
  • 9