OWolf
OWolf

Reputation: 5132

How to get an instance of my view controller from the app delegate, storyboards, iOS6

Trying to "instantiate" my initial view controller from the app delegate. I trying to populate an NSMutableArray from the app delegate. A property of the view controller "myMutabelArray" gets an array that is created within the app delegate. With the code below the array is uneffected, even though it's count is 4 (has four objects), as created in the app delegate.

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle: nil];
ViewController *controller = (ViewController*)[mainStoryboard instantiateInitialViewController];
controller.myMutableArray = mutableArrayCreatedInAppDelegate;

When I log the count from within the AppDelegate I get 4. When I log the count from within the ViewController I get 0.

I also tried the following which makes me suspect that I am not getting a pointer to the view controller as needed.

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle: nil];
ViewController *controller = (ViewController*)[mainStoryboard instantiateInitialViewController];
[controller.view setBackgroundColor:[UIColor lightGrayColor]];

Upvotes: 0

Views: 5264

Answers (1)

Levi
Levi

Reputation: 7343

Try the following:

ViewController *controller = (ViewController*)self.window.rootViewController;

It will return the initial view controller of the main storyboard.

Upvotes: 5

Related Questions