Search code examples
objective-ciosxcode4uiviewcontroller

Access class variable from another class


I have a UITabBarController that manages two ViewControllers. The first is a UIViewController that allows the user to change game settings. The second is a GLKViewController that runs the game simulation.

I'm trying to enable the Game ViewController to fetch the settings from the Settings ViewController. I have a Slider on the Settings View that represents "Speed".

I have a reference to the other controller, but I'm unable to expose the variable that backs my Slider properly.

SecondViewController.h

@interface SecondViewController : UIViewController{
    IBOutlet UISlider    * mySlider;
}
property (nonatomic,retain) IBOutlet UISlider    * mySlider;
@end

SecondViewController.m

- (IBAction) mySliderWasMoved:(id)sender;
@implementation SecondViewController
@synthesize mySlider;
- (IBAction) mySliderWasMoved:(id)sender{    
};

ThirdViewController.m

NSArray *tmpVCs = self.parentViewController.tabBarController.viewControllers;
UIViewController *tmpVC = [tmpVCs objectAtIndex:1]; //obtain handle to SecondViewController
//NSNumber *mySpeed = tmpVC.mySlider;  //doesn't see mySlider
NSNumber *mySpeed = [tmpVC mySlider];  //doesn't see mySlider

I'm new to this, and there are many aspects of my project to learn - so I'm not trying to learn how to manage data at this time. I just need to know how to access an instance variable


Solution

  • Fort the benefit of others: I grabbed a handle to the other class, but I hadn't declared the return type as the correct type of class.

    Replace:

    UIViewController *tmpVC = [tmpVCs objectAtIndex:1]; 
    

    With:

    SecondViewController *tmpVC = [tmpVCs objectAtIndex:1]; 
    

    Now I have access to the properties that are specific to the SecondViewController.