【发布时间】:2017-01-26 04:02:49
【问题描述】:
在 Swift 3 中,dispatch_once 函数被移除,migration guide 建议使用初始化闭包:
让 myGlobal = { ... global 包含对闭包的调用中的初始化 ... }()
_ = myGlobal // 使用 myGlobal 只会在第一次使用时调用初始化代码。
我想从初始化闭包中访问“self”实例变量,如下所示:
class SomeClass {
var other = SomeOtherClass()
let initialize: () = {
// self.other - this doesn't work, complains about unresolved identifier 'self'
// how to access self.other here?
} ()
func doSomething() {
// initialize will only be called once
initialize
}
}
为什么在闭包中无法访问“self”,如何才能访问?
【问题讨论】:
-
将 dispatch_once 与实例属性一起使用以确保“每个实例一次”初始化总是错误的,例如,请参阅 Apple 工程师的回答 stackoverflow.com/a/19845164/1187415。
-
那么在 Swift 3 中确保实例初始化代码只运行一次并且能够设置实例变量的正确方法是什么?在这种情况下,我不能使用 init() 的变体,因为类 (NSViewController) 只需要运行一次初始化代码,但在
NSViewController生命周期中的某个点之后(即viewDidAppear)。您认为@vadian 提供的答案是否正确(似乎工作正常)?