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) Define static variables in global.h. E.g. you want to have a NSString global variable, declare the following in global.h:
@interface global : NSObject {
}
+(NSString*)MY_STR;
@end
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;
}
Then in any class that needs this variable, you can import global.h and access it as below:
[global MY_STR];
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
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
In any class that needs to access MY_STR, import global.h and write the following:
global *g1= [global getInstance];
g1.MY_STR;
3) The third approach would be to declare variables in app delegate and access them.
for a (not-objective) c approach:
in global.h
extern int flag;
in global.m
int flat;
in any other .m or .c
#import "global.h"
flag = 123; // set
int abc = flag; // get