Please help, I’m stuck with objective-c global variables aka extern!
I writing my first iOS app it is a game, so to save my progress I wrote some global variables in Globals.h:
@interface Globals : NSObject
extern float square;
extern float field;
extern float dx;
extern float dy;
extern NSURL *documentsUrl;
extern NSURL *dbUrl;
extern NSString *savePath;
extern FMDatabase *db;
@end
And Globals.m:
#import "Globals.h"
@implementation Globals
float square;
float field;
float dx;
float dy;
NSURL *documentsUrl;
NSURL *dbUrl;
NSString *savePath;
FMDatabase *db;
+(void)initialize
{
static BOOL initialized = NO;
if (!initialized)
{
initialized = YES;
square = 177.7778;
field = 146.0;
dx = 105;
dy = 58.5;
documentsUrl = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
dbUrl = [documentsUrl URLByAppendingPathComponent:@"alias.sql"];
[[NSFileManager defaultManager] copyItemAtURL:[[NSBundle mainBundle] URLForResource:@"alias" withExtension:@"sql"] toURL:dbUrl error:nil];
savePath = [[documentsUrl URLByAppendingPathComponent:@"save.plist"] path];
db = [FMDatabase databaseWithPath:[dbUrl path]];
//db.logsErrors = YES;
//db.traceExecution = YES;
if (![db open]) {
NSLog(@"Could not open db.");
}
}
}
@end
I make asured that initialize method executes at least once as app launched. In MainViewController which is my RootViewController in viewDidLoad method I use:
[GameInfo hasSave];
Which is a static method in GameInfo class and look like:
+(BOOL)hasSave
{
return [[NSFileManager defaultManager] fileExistsAtPath: savePath];
}
And when I trace it the savePath is something like:
/Users/Apple/Library/Application Support/iPhone Simulator/5.0/Applications/472969F1-3760-4C74-8C8D-29681F47F4CB/Documents/save.plist
But then I execute IBAction on Touch up inside in the same view, in the same time which look like:
if ([GameInfo hasSave])
{
[GameInfo load];
}
And when I make a step in method hasSave I have some strange savePath value:
ar.lproj
And my method of course returns me NO. But it occurs not only with my savePath, but with all other extern variables. And sometimes they are correct but sometimes they are not.
I think maybe the problem is where I use them, maybe I forgot something to do. Please help me.
P.S.: Sorry about my English and a huge quastion.
your
[[NSFileManager defaultManager] fileExistsAtPath: savePath];will returnNOas there exits thesavePathbut there doesn’t exists the file as you haven’t created it in~~~~~~~~~~~~~~~~~ edited ~~~~~~~~~~~~~~~~~~~~
use
extern NSString *savePath;in your GameInfo.h or .m