简体   繁体   中英

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

As mention on the comments,

  1. Use NSDefault to save the value on slider changed. On the very first time of loading your application, you will want to set a default value.

  2. Use Singleton Object to store value.

We understand that, quoting from you " not trying to learn data persistence at this time. Nor do I need architecture direction.", but the rule of thumb here is that you probably will be able to access the instance variable in some way or the other but i think having the best approach will benefit you greatly.

Just my 2 cent.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM