我是 GCD 的新手,似乎简单的使用它对我不起作用。我有以下代码:
+ (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 = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(synchronizationTimerFired:) userInfo:nil repeats:YES];
}
}
}
日志显示“顶部”,没有其他内容。中间的代码没有无限循环——它永远不会一直执行。我可以在中间的代码中设置断点,程序执行会中断,之后不会中断。中间有一个点,有时执行会在断点处停止,有时则不会。
在我看来,synchronizationQueue 调度队列似乎正在被释放,但我不能调用 dispatch_retain,因为编译器抱怨 dispatch_retain 不能在 ARC 中使用。我错过了什么?
作为对人们询问中间代码的回应,程序执行在此方法调用中停止(由...code...的这些行之一表示)在 if (fetchArray.count) 行中,注释如下.
+ (NSDate *)latestParseReceivedDownUpdatedAtDateForCoreDataEntityNameString:(NSString *)coreDataEntityNameString
{
NSDate *functionReturnValue = nil;
// Create fetchRequest
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:coreDataEntityNameString];
// Set sort descriptor
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"parseReceivedDownUpdatedAtDate" ascending:NO]]];
// We are only interested in one result
[fetchRequest setFetchLimit:1];
// Execute fetchRequest
NSError *fetchError = nil;
NSArray *fetchArray = [JBSAPPDELEGATE.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
if (fetchArray == nil)
{
NSLog(@"Unresolved error %@, %@", fetchError, [fetchError userInfo]);
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 = [fetchArray objectAtIndex:0];
functionReturnValue = [managedObject valueForKey:@"parseReceivedDownUpdatedAtDate"];
}
return functionReturnValue;
}
我会补充一点,如果我简单地注释掉对 dispatch_async 的调用,那么一切都可以正常执行。它只是在主线程上执行,我宁愿让它不这样做。