rob5408
rob5408

Reputation: 2982

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

Upvotes: 14

Views: 40897

Answers (3)

Marc Charbonneau
Marc Charbonneau

Reputation: 40507

Your NSLog() statement is "seeing" it as a MainViewController because that's what the object actually is. The problem you're having though, is that the compiler doesn't actually realize this because the parentViewController property is declared as a plain old UIViewController. Even though you're actually returning a subclass of it, as far as the compiler knows you're trying to call that method on a UIViewController, and it's going to complain. Casting it to a MainViewController will solve the issue.

Upvotes: 1

Tim Kozak
Tim Kozak

Reputation: 4182

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];

Upvotes: 4

Ed Marty
Ed Marty

Reputation: 39690

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.

Upvotes: 29

Related Questions