如何判断方法是否异步运行?
我有几个与核心数据相关的方法,这些方法有时通过异步调度队列 (GCD) 异步调用,有时则同步调用。
// sometimes this happens
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[[DataServices sharedInstance] doSomeCoreDataStuff:^(BOOL result, NSString *message)
{
// do some post-stuff here
}];
});
// other times this happens
[[DataServices sharedInstance] doSomeCoreDataStuff:^(BOOL result, NSString *message)
{
// do some post-stuff here
}];
除此之外,我还在整个应用程序中使用了单例 NSManagedObjectContext
。由于上下文不是线程安全的,在核心数据方法异步运行的情况下,我需要在这些方法中创建一个新的上下文,否则我想使用单例实例上下文。
想到的唯一方法是类似[[NSThread mainThread] isMainThread]
,但是 GCD 可能会也可能不会在主线程上工作,所以这行不通。
最佳答案
处理这个问题的正确方法是将您的托管对象上下文配置为使用一种线程限制并发类型——NSPrivateQueueConcurrencyType
或 NSMainQueueConcurrencyType
——然后使用它的performBlock:
方法,当你想使用它的时候。也就是说,
[[DataServices sharedInstance] performBlock:^{
// do Core Data stuff here
}];
您可以在任何线程或队列上执行此操作,而且它是异步的。还有 performBlockAndWait:
如果您需要立即得到结果。
你会在任何地方使用那个电话。唯一的异常(exception)是,如果你使用 NSMainQueueConcurrencyType
并且你知道你正在主队列上运行,你可以直接调用上下文而不是通过 performBlock :
关于iOS5 : Determine if core data method is running in an asynch dispatch queue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15161853/