我有一种方法,每次调用它时都需要延迟 5 秒。首先,我使用它sleep(5);
——它工作得很好,但我相信——它不是 obj-c 方式,所以我尝试在 GCD 的帮助下编写它。此过程的第一次调用会延迟大约 5 秒,但此队列中的其他调用会一个接一个地进行,没有延迟。如何解决这个问题呢?
- (void) buyItemAtUUID:(NSString*)UUID
{
dispatch_barrier_async(dataManagerQueue, ^{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dataManagerQueue, ^(void){
NSInteger path = [self indexFromObjectUUID:UUID];
if (path != NSNotFound)
{
NSMutableDictionary *item = [[_items objectAtIndex:path] mutableCopy];
NSNumber *value = [NSNumber numberWithFloat:[[item objectForKey:@"Quantity"] floatValue] - 1.0];
}
});
});
}