Loading 2 Singletons With Dependencies when an app is opened (appDelegate / appDidBecomeActive) iPhone SDK

Posted by taber on Stack Overflow See other posts from Stack Overflow or by taber
Published on 2011-03-15T21:51:42Z Indexed on 2011/03/16 0:10 UTC
Read the original article Hit count: 222

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];

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c