How to access a variable's value from one class, if the variable is defined in another? (Objective-C)
I have two pairs (.m and .h) of files. In one's interface section, I've defined a global BOOL variable. I need to get it's value in another class. How can I do it? (I can't make one class a subclass of another).
In one file I have
@interface TabBarRotation : UITabBarController {
BOOL portrait;
}
@end
@implementation TabBarRotation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void):(UIInterfaceOrientation) interfaceOrientation {
if (interfaceOrientation == UIInterfaceOrientationPortrait||interfaceOrientation == UIInterfaceOrientat开发者_开发问答ionPortraitUpsideDown) {
portrait=YES;
}
else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
portrait=NO;
}
}
@end
And in another's @implementation I have
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if(portrait==YES) {
CalcPortraitViewController *CalcPortraitController;
CalcPortraitController = [[CalcPortraitViewController alloc]
initWithNibName:@"CalcPortraitView" bundle:nil];
CalcPortraitController.title=@"Калькулятор";
CalcPortraitController.hidesBottomBarWhenPushed=YES;
[self.navigationController pushViewController:CalcPortraitController
animated:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
}
else if (portrait==NO) {
CalcLandscapeViewController *CalcLandscapeController;
CalcLandscapeController = [[CalcLandscapeViewController alloc]
initWithNibName:@"CalcLandscapeView" bundle:nil];
CalcLandscapeController.title=@"Калькулятор";
CalcLandscapeController.hidesBottomBarWhenPushed=YES;
[self.navigationController pushViewController:CalcLandscapeController
animated:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
}
}
If you really want a global variable, you don't want it to be in the interface of either class. You can access global variables just like you would in C. Use:
extern BOOL myGlobal;
to declare the variable anywhere you need to use it (or in a common header might be ideal). Then define it in exactly one place:
BOOL myGlobal;
And you should be set.
If you do want it to be an instance variable of a class, you can make an accessor like you normally would to get at that variable from another class.
精彩评论