ios - dispatch_async 永远不会完成整个 block 的执行
<p><p>我是 GCD 的新手,似乎简单的使用它对我来说不起作用。我有以下代码:</p>
<pre><code>+ (void)synchronizationTimerFired:(NSTimer *)theTimer
{
if ((synchronizationUpNeededFlag) || (synchronizationDownNeededFlag))
{
if ((!synchronizationUpInProgressDepthQuantity) && (!synchronizationDownInProgressDepthQuantity))
{
dispatch_queue_t synchronizationQueue = dispatch_queue_create("synchronizationQueue",NULL);
dispatch_async(synchronizationQueue, ^(void) {
NSLog(@"Top");
...code...
...code...
...code...
NSLog(@"Bottom");
});
}
}
// Check if there is no timer, or if it is not currently valid,
// and yet if synchronization is turned on,
// then establish a repeating timer to attend to synchronization related matters.
if ((!synchronizationTimer) || (!synchronizationTimer.isValid))
{
if (synchronizationOnFlag)
{
synchronizationTimer = ;
}
}
}
</code></pre>
<p>日志显示“顶部”,没有其他内容。中间的代码没有无限循环——它永远不会一直执行。我可以在中间的代码中设置断点,程序执行会中断,之后不会中断。中间有一个点,有时执行会在断点处停止,有时则不会。</p>
<p>在我看来,synchronizationQueue 调度队列似乎正在被释放,但我不能调用 dispatch_retain,因为编译器提示 dispatch_retain 不能在 ARC 中使用。我错过了什么?</p>
<p>响应人们询问中间代码的问题,程序执行在此方法调用中停止(由...code...的这些行之一表示)在 if (fetchArray.count) 行,在下面评论。</p>
<pre><code>+ (NSDate *)latestParseReceivedDownUpdatedAtDateForCoreDataEntityNameString:(NSString *)coreDataEntityNameString
{
NSDate *functionReturnValue = nil;
// Create fetchRequest
NSFetchRequest *fetchRequest = ;
// Set sort descriptor
]];
// We are only interested in one result
;
// Execute fetchRequest
NSError *fetchError = nil;
NSArray *fetchArray = ;
if (fetchArray == nil)
{
NSLog(@"Unresolved error %@, %@", fetchError, );
abort();
}
// If there are any records at all in our persistent store, we'll have exactly one.
// But that doesn't mean it won't be nil, as if that record has never come down from
// parse it will be a nil date on the managed object.
if (fetchArray.count) // PROGRAM EXECUTION STOPS EITHER HERE, OR JUST BEFORE HERE
{
NSManagedObject *managedObject = ;
functionReturnValue = ;
}
return functionReturnValue;
}
</code></pre>
<p>我会补充一点,如果我简单地注释掉对 dispatch_async 的调用,那么一切都可以正常执行。它只是在主线程上执行,我宁愿不这样做。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你的 managedObjectContext 是 NSManagedObjectContext 吗?如果是这样,您是否在用于调度队列的特定线程上创建了托管对象上下文?如果您阅读 NSManagedObjectContext 上的文档,它会说:</p>
<blockquote>
<p>...a context assumes the default owner is the thread or queue that
allocated it—this is determined by the thread that calls its init
method. You should not, therefore, initialize a context on one thread
then pass it to a different thread. Instead, you should pass a
reference to a persistent store coordinator and have the receiving
thread/queue create a new context derived from that.</p>
</blockquote></p>
<p style="font-size: 20px;">关于ios - dispatch_async 永远不会完成整个 block 的执行,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/19747960/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/19747960/
</a>
</p>
页:
[1]