在SpriteKit中,touchesBegan在与SKScene更新方法相同的线程中运行吗?
在此处的Apple文档高级场景处理中描述了更新
方法以及如何渲染场景,但没有提到何时处理输入。目前尚不清楚它是否与渲染循环在同一个线程中,或者它是否与它并发。
In the Apple documentation here Advanced Scene Processing it describes the update
method and how a scene is rendered, but it does not mention when input is processed. It is not clear if this is in in the same thread as the rendering loop, or whether it is concurrent with it.
如果我有一个我从两个更新的对象 SKScene
更新
方法和 touchesBegan
方法(在此处一个 SKSpriteNode
的情况)我是否要担心同步对我的对象的两次访问?
If I have an object that I update from both the SKScene
update
method and the touchesBegan
method (in this case of a SKSpriteNode
) do I have to worry about synchronising the two accesses to my object?
所以几天后没有回答我设置了一些实验。顺便说一句,这些测试是在模拟器上运行而不是在实际设备上运行,但我认为它们是相同的。
So after a few days with no answer I set up some experiments. By the way, these tests are run on the simulator and not on an actual device, but I think it would be the same.
首先测试,我设置了一个断点 touchesBegan
上的调试器,并查看堆栈跟踪。看来 touchesBegan
是从第一个线程和 main
循环中调用的 - 与其余部分相同的地方逻辑,所以这看起来很适合单线程方法。
First test, I set a breakpoint in the debugger on touchesBegan
and looked at the stack trace. It appears that touchesBegan
is called from the first thread and from the main
loop - the same place as the rest of the logic, so this looks good for a singe-threaded approach.
第二次测试,我覆盖高级场景处理中提到的场景中的各种方法链接上面并添加了print语句以显示所调用的每个函数的名称。然后我在 touchesBegan
方法中添加了一个print语句。
Second test, I overrode the various methods in the scene mentioned in the Advanced Scene Processing link above and added print statements to show th name of each function called. Then I added a print statement to the touchesBegan
method.
在运行应用程序时,输出为:
On running the app, the output was:
update
didEvaluateActions
didSimulatePhysics
didApplyConstraints
didFinishUpdate
touchesBegan in scene
update
didEvaluateActions
didSimulatePhysics
didApplyConstraints
didFinishUpdate
update
每当我点击时都会重复这种模式。
and this pattern was repeated whenever I clicked.
没有任何点击给了我除了 touchesBegan
在 didFinishUpdate
(即一个周期结束)和更新
之间调用(下一个开头)。
No amount of clicking gave me anything else than touchesBegan
being called between the didFinishUpdate
(that is, the end of one cycle) and the update
(the beginning of the next).
结论:在调用update方法之前,在主循环中进行触摸处理。因此,没有必要在两种方法之间同步资源。
Conclusion: touches processing happens in the main loop before the update method is called. It is therefore not necessary to synchronise resources between the two methods.