gpt4 book ai didi

swift - 如何在 Swift 中只执行一次代码?

转载 作者:IT王子 更新时间:2023-10-29 05:18:15 25 4
gpt4 key购买 nike

到目前为止我看到的答案(123)推荐使用 GCD 的dispatch_once因此:

var token: dispatch_once_t = 0
func test() {
dispatch_once(&token) {
print("This is printed only on the first call to test()")
}
print("This is printed for each call to test()")
}
test()

输出:

This is printed only on the first call to test()
This is printed for each call to test()

但等一下。 token是一个变量,所以我可以很容易地做到这一点:

var token: dispatch_once_t = 0
func test() {
dispatch_once(&token) {
print("This is printed only on the first call to test()")
}
print("This is printed for each call to test()")
}
test()

token = 0

test()

输出:

This is printed only on the first call to test()
This is printed for each call to test()
This is printed only on the first call to test()
This is printed for each call to test()

所以 dispatch_once如果我们可以更改 token 的值,则没有用!和车削token转换成常量并不简单,因为它需要 UnsafeMutablePointer<dispatch_once_t> 类型.

那么我们应该放弃dispatch_once吗?在 swift ?有没有更安全的方法只执行一次代码?

最佳答案

一个人去看医生,说“医生,我踩脚的时候很痛”。医生回答说,“所以不要再做了”。

如果您故意更改您的调度 token ,那么是的 - 您将能够执行代码两次。但是,如果您围绕旨在防止以任何 方式多次执行的逻辑,您将能够做到这一点。 dispatch_once 仍然是确保代码只执行一次的最佳方法,因为它处理所有(非常)复杂的围绕初始化和竞争条件的极端情况,而简单的 bool 值无法涵盖这些情况。

如果您担心有人可能会不小心重置 token ,您可以将其包装在一个方法中,并使其尽可能明显地说明后果。像下面这样的东西会将 token 限定在方法范围内,并防止任何人未经认真努力就更改它:

func willRunOnce() -> () {
struct TokenContainer {
static var token : dispatch_once_t = 0
}

dispatch_once(&TokenContainer.token) {
print("This is printed only on the first call")
}
}

关于swift - 如何在 Swift 中只执行一次代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34203623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com