全局变量问题 [英] Global Variable problem
问题描述
我在global.h文件中定义了一个全局变量标志,当我单击下一个选项卡栏时我无法访问该标志值.我想要所有选项卡的全局变量.请建议我.
I define a global variable flag in global.h file,when i click next tab bar then i can not access the flag value.I want a global variable for all tabs.please suggest me.
推荐答案
如果您要使用全局变量,可以尝试以下方法:
If you want a global variable, here are some options you can try:
1)在global.h中定义静态变量.例如.您要使用NSString全局变量,请在global.h中声明以下内容:
@interface global : NSObject {
}
+(NSString*)MY_STR;
@end
然后在global.m中将其实现为静态:
Then implement it as static in global.m:
static NSString* MY_STR;
@implementation global
+(void) initialize
{
MY_STR = @"global string";
}
+(NSString*)MY_STR{
return MY_STR;
}
然后在需要此变量的任何类中,您都可以导入global.h并按以下方式访问它:
Then in any class that needs this variable, you can import global.h and access it as below:
[global MY_STR];
2)在这种方法中,定义一个单例类并使用其属性. 您可以将global创建为单例类.在global.h中声明一个静态的getInstance方法:
2) In this approach, define a singleton class and use its properties. You can create global as a singleton class. Declare a static getInstance method in global.h:
@interface global : NSObject{
NSString *MY_STR;
}
@property(nonatomic, retain) NSString *MY_STR;
+(global*)getInstance;
@end
在global.m中,声明一个静态sharedInstance:
In global.m, declare a static sharedInstance:
@implementation global
@synthesize MY_STR;
static global *g;
+(global*)getInstance{
@synchronized([global class]){
if(g == nil){
g = [[global alloc] init];
}
}
return g;
}
@end
在需要访问MY_STR的任何类中,导入global.h并编写以下内容:
In any class that needs to access MY_STR, import global.h and write the following:
global *g1= [global getInstance];
g1.MY_STR;
3)第三种方法是在应用程序委托中声明变量并访问它们.
这篇关于全局变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!