我有一个ios 6应用程序,它在应用程序代理中实例化了3个单例,如下所示:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
Constants *constSingleton = [Constants getSingleton];
EntryContainerSingleton * eSingle = [EntryContainerSingleton getSingleton];
LocationMgrSingleton *loc = [LocationMgrSingleton getSingleton];
return YES;
}
然而,问题是这三个调用同时在不同的线程中执行。EntryContainerSingleton依靠常量来完成一些任务。但是,在执行这些任务时,常量并没有完全实例化。
我该如何处理这种情况?我在谷歌上搜索,在以前版本的iOS中,人们使用NSOperation队列来完成这项工作。
然而,我不确定这在iOS 6中是否是一个好方法。即使是这样,我以前也没有使用过NSOperation队列,web上的所有示例都来自以前的版本,并且在某个类中实例化,而该类不是APP Delegate。
如果有人能给我一些关于如何在App Delegate中做到这一点的示例代码,让我开始,我真的很感激
编辑
条目控制器单例
-(id)init
{
self = [super init];
NSLog(@"%s %d", __PRETTY_FUNCTION__, __LINE__);
[self getEntriesFromServer];
..............
.............
constSingleton = [Constants getSingleton];
[self addSelfAsObserverToNotifications];
return self;
}
内部入口控制器
-(void)getEntriesFromServer
{
NSLog(@"%s %d", __PRETTY_FUNCTION__, __LINE__);
if(!constSingleton)
{
NSLog(@"constSingleton is null");
}
__block NSString *dateString1 = [constSingleton getCurrentDateTime];
NSLog(@"Sending notification: Async Call started successfully at time %@", dateString1);
[[NSNotificationCenter defaultCenter] postNotificationName:@"didStartAsyncProcess"
object:self];
.......
}
控制台输出
[96894:c07] -[AppDelegate application:didFinishLaunchingWithOptions:] 21
[96894:c07] +[Constants getSingleton] 39
[96894:c07] -[Constants init] 65
[96894:c07] -[EntryContainerSingleton init] 75
[96894:c07] -[EntryContainerSingleton getEntriesFromServer] 154
[96894:c07] constSingleton is null
[96894:c07] Sending notification: Async Call started successfully at time (null)
[96894:c07] -[Constants incrementNumBackgroundNetworkTasksBy1:] 87
如果Entries singleton需要访问Constants singleton,它应该调用[Constants getSingleton]来获得它。确保您正确地实现了您的singleton方法(请参阅Objective-C singleton实现,我做得对吗?)
每次需要访问singleton对象时,都应该调用[ClassNamegetSingleton]。不应该有任何理由将singleton作为实例变量存储在应用程序委托中。