且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift:更新UI-主线程上的整个函数还是UI更新?

更新时间:2023-01-13 10:47:46

首先,您的 undoPressed 方法将在主队列上调用.

First off, your undoPressed method will be called on the main queue.

在第一组代码中,所有内容都将放在主队列中.

In the first set of code, everything will be on the main queue.

在第二组代码中,使用 DispatchQueue.main.async 是没有意义的,因为其余代码已在主队列中.

In the second set of code, using DispatchQueue.main.async is pointless since the rest of the code is already on the main queue.

所以实际上,您仅有的两个明智的选择是1和3.

So really your only two sensible options are 1 and 3.

给出您的代码,选项1很好.如果在后台运行的代码花费的时间不多,那么您只想使用选项3.由于您这里的代码很简单,几乎不需要时间来执行,因此这里的选项3没有意义.

Given your code, option 1 is fine. You would only want to use option 3 if the code being run in the background took more than a trivial amount of time to execute. Since the code you have here is trivial and will take virtually no time to execute, there is no point in option 3 here.

因此,只需使用第一组代码,就可以了.

So simply use your first set of code and you'll be fine.

担心在需要执行大循环或计算复杂算法或执行任何类型的网络访问时将代码移至后台.

Worry about moving code to the background when it need to perform a big loop or calculate a complicated algorithm or perform any sort of network access.