当我的iPhone应用程序加载时,我正在尝试加载两个标准问题风格的单例:http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html。这是我的代码:
- (void) applicationDidFinishLaunching:(UIApplication *)application {
// first, restore user prefs
[AppState loadState];
// then, initialize the camera
[[CameraModule sharedCameraModule] initCamera];
}
我的“相机模块”具有检查AppState单例属性的代码。但我认为正在发生的是竞争条件,其中相机模块单身人员正在尝试访问AppState属性,而它正处于初始化状态(因此该属性为nil,并且它正在重新初始化AppState)。我真的想将这些分开,而不是仅仅将一个(或两个)投入到App Delegate中。有没有人见过这样的东西?你使用了什么样的解决方法,或者你会建议什么?
提前致谢!
这是loadState方法:
+ (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];
}
}
}
在CameraModule中调用AppState的行:
- (void)initCamera {
...
if([AppState sharedAppState].captureSession != nil) {
...
}
}
答案 0 :(得分:0)
最奇怪的事情正在发生......我正在AppState
访问RootViewController
的{{1}}属性,应用程序执行的顺序是罪魁祸首。
RootViewController
加载到我的MainWindow.xib文件中,显然XIB加载/ shenanegans发生在applicationDidFinishLaunching
内的任何内容之前,因此在游戏后期调用了loadState。
解决方案是将[AppState loadState]
移动到我的RootViewController
的init方法。