示例 Objective-C 代码以有效地对线程安全回调进行排队

Sample Objective-C code to queue thread-safe callbacks efficiently

我正在查看 Apple 的 GCD 指南,发现它对于我想要实现的目标来说相当冗长。我正在开发一个 iOS SpriteKit 游戏(使用 Objective-C),我需要为 2 个简单任务使用并发:

在这两种情况下,都没有并发相关数据损坏的风险,我也不需要执行跨线程通信(不需要任何同步)。

带有示例代码的答案将是完美的。

我不确定它会更有效率,但会产生更好的代码...

系统提供了一些带有 gcd 的默认后台队列,您可以使用它们而不是创建自己的队列,然后它会处理将队列上的事情卸载到其他线程,当它认为它会是最有益的。要实现这一点非常简单:

----SWIFT----

// Dispatch a block of code to a background queue
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) { 
    // Do initialisation in the background
    ...
    // Call back to the main queue if you want to update any UI when you are done
    dispatch_sync(dispatch_get_main_queue()) {
        // Set progress indicator to complete?
    }
}
// Handle the progress indicator while the initialisation is happening in the background

---- OBJ-C ----

// Dispatch a block of code to a background queue
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, { 
    // Do initialisation in the background
    ...
    // Call back to the main queue if you want to update any UI when you are done
    dispatch_sync(dispatch_get_main_queue(), {
        // Set progress indicator to complete?
    });
});
// Handle the progress indicator while the initialisation is happening in the background

非常简单,这将初始化分派到后台队列,并在完成后回调主线程,然后继续更新进度指示器。

请务必记住,您不得从主队列以外的任何队列更新 UI。

希望这对您有所帮助,让我知道是否可以更清楚。