Accessing parent view controller (custom) properties

后端 未结 3 1053
死守一世寂寞
死守一世寂寞 2020-12-24 08:40

I have written a UITabBarController subclass (called MainViewController) and added a few instance variables, specifically a venue of type Venue. Ea

相关标签:
3条回答
  • 2020-12-24 09:24

    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.

    0 讨论(0)
  • 2020-12-24 09:35

    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.

    0 讨论(0)
  • 2020-12-24 09:43
    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];
    
    0 讨论(0)
提交回复
热议问题