Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing parent view controller (custom) properties

I have written a UITabBarController subclass (called MainViewController) and added a few instance variables, specifically a venue of type Venue. Each tab of the MainViewController needs to access the venue variable of the MainViewController. In the first tab, a UIViewController subclass named HomeViewController, I wrote my viewDidLoad method and tried to output to NSLog with both...

NSLog(@"%@", self.parentViewController.venue.name);

and

NSLog(@"%@", self.tabBarController.venue.name);

But XCode gives the error

error: request for member 'venue' in something not a structure or union

I can access the venue property from within MainViewController just fine so have ruled out an error there. The iPhone simulator does see both self.parentViewController and self.tabBarController as an instance of MainViewController. The line...

NSLog(@"%@", self.tabBarController);

outputs...

2009-06-05 17:54:46.502 Venue[29729:20b] <MainViewController: 0x536600>

Since it's seen as a MainViewController instance, I doubt using casting would help. Is my only other option to initialize the HomeViewController with a copy of the venue or am I just doing something completely wrong with 'self.parentViewController.venue.name'? Thanks, Rob

like image 480
rob5408 Avatar asked Jun 05 '09 17:06

rob5408


2 Answers

You're doing something completely wrong. parentViewController is declared as a UIViewController. NSLoging it outputs its real type due to the wonders of polymorphism.

UIViewController doesn't have a Venue member. Your MainViewController does. Casting it is, in fact, the right answer. Make sure to import MainViewController.h as well.

#import "MainViewController.h"
[...]
NSString *name = ((MainViewController *)self.parentViewController)).venue.name;

Also make sure, of course, that venue is declared as a @property of MainViewController, and name is a @property of Venue.

like image 168
Ed Marty Avatar answered Nov 05 '22 02:11

Ed Marty


int currentVCIndex = [self.navigationController.viewControllers indexOfObject:self.navigationController.topViewController];

//previous view controller
AccountViewController *account = (AccountViewController *)[self.navigationController.viewControllers objectAtIndex:currentVCIndex - 1];

account.property = object;
[account doSmthng];
like image 4
Tim Kozak Avatar answered Nov 05 '22 02:11

Tim Kozak