Loading 2 Singletons With Dependencies when an app is opened (appDelegate / appDidBecomeActive) iPhone SDK
- by taber
I'm trying to load two standard-issue style singletons: http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html when my iPhone app is loaded. Here's my code:
- (void) applicationDidFinishLaunching:(UIApplication *)application {
// first, restore user prefs
[AppState loadState];
// then, initialize the camera
[[CameraModule sharedCameraModule] initCamera];
}
My "camera module" has code that checks a property of the AppState singleton. But I think what's happening is a race condition where the camera module singleton is trying to access the AppState property while it's in the middle of being initialized (so the property is nil, and it's re-initializing AppState). I'd really like to keep these separate, instead of just throwing one (or both) into the App Delegate. Has anyone else seen something like this? What kind of workaround did you use, or what would you suggest?
Thanks in advance!
Here's the loadState method:
+ (void)loadState {
@synchronized([AppState class]) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingPathComponent:@"prefs.archive"];
Boolean saveFileExists = [[NSFileManager defaultManager] fileExistsAtPath:file];
if(saveFileExists) {
sharedAppState = [[NSKeyedUnarchiver unarchiveObjectWithFile:file] retain];
} else {
[AppState sharedAppState];
}
}
}