开发者

iphone global var goes null

I have a globals.h and my appdelegate.h and m.

In the globals.h I have:

extern NSString  *databasePath;

in appdelegate.h I have

NSString *databasePath;

in appdelegate.m I assign a value and print it:

    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

NSLog(@"Database is:%@", databasePath);

All is good up to this point. When I call another class and display the data the same way the databasePath is gone.

However if I make assign databasePath like this, 开发者_StackOverflow社区then it works and I am able to use NSLog to show the value:

databasePath =@"XYZZY";

What am I doing wrong?


Your question is a bit ambiguous, so I'm going to give you two answers here. You might want to clarify your question. :)

C globals don't work that way.

Others seem to be making the assumption that you have the NSString *database in your class. But I'm going to take your question at face value and assume you have it loose in appdelegate.h.

(Incidentally, that makes this a C problem, not an Objective-C one.)

What's happening is that each time appdelegate.h is being imported, the .m file ultimately responsible for the import is getting a new copy of it.

You should have extern in appdelegate.h as well. The non-extern NSString *database must be in a .m file.

Objective-C doesn't work that way.

The other possibility is, of course, that you really do have NSString *database in your class. That makes it not a global variable, but an instance variable. You can't declare it as a global by using extern NSString *database in another header. What you're doing, then, is setting the instance variable in your AppDelegate and accessing a same-named global from your other class.

Remove the global entirely and just use your AppDelegate. You can read it using an accessor.

Something like:

id appDelegate = [[UIApplication sharedApplicaiton] delegate];
id databasePath = [appDelegate databasePath];


[documentsDir stringByAppendingPathComponent:databaseName] returns an unowned string. It will have been wiped from memory before you try to use it later. In general case, this could cause an EXC_BAD_ACCESS type of crash. If you'd like to use the string at a later time, copy or retain it to get ownership over it. You may want to release it in the app delegate's dealloc method (or before assigning another value to your global var).

In the case with @"XYZZY", you're using a constant string literal which persists in memory for the whole app lifetime. That's why it works as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜