Reputation: 4467
I load a few variables in my appdelegate class. They are declared in my .h file.
I have a global.h
file that declares the same vars as extern
, such as:
NSString *DBName;
extern NSString *DBName;
I haven't found the pattern yet, but some of the classes I include the global.h
but the var is nil.
Any idea what I am doing wrong?
It looks like the vars that are like:
int x;
stick and are available, but the vars that are pointers get lost:
NSString *Name;
They are all loaded initially from a DB in the appdelegate.
I also tried declaring
char Name[30];
then assigning it and all is good.
Now what?
Upvotes: 3
Views: 7978
Reputation: 4467
Problem was the NSStrings were not retained. @xianritchie suggested this in the comment above. I changed the few global strings I have an now all is good.
Thanks all for the help
Upvotes: 0
Reputation: 162722
In a .h:
extern NSString *global;
In a .m somewhere:
NSString *global = @"foobar";
If you need to set the global at runtime, you'll have to do so in a method somewhere; say, applicationDidFinishLaunching:
.
Where are you assigning to the global in the NSString case? And when you do are you retaining the value? What do you mean by "lost"?
Note that the variable must not be declared in a .h; the extern goes in the .h, the NSString *global;
must be in one and only one .m file.
Upvotes: 4
Reputation: 331
What kind of variables are your working with? Are they primitives or objects? If they are primitives, you might think about preprocessor define statements rather than global variables.
If they are objects, you may want to create an implementation of your Global class, and use a Singleton instance to serve and set the variables. Something similar to this
@implementation Global
static Global *myGlobal = nil;
+(Global *)sharedInstance
{
if (myGlobal == nil) {
myGlobal = [[self alloc] init];
}
return myGlobal;
}
@end
Then you can call the variables using:
[[Global sharedInstance] variableName]
Upvotes: 1