gpt4 book ai didi

ios - 为什么我用闭包初始化属性时可以使用 self?

转载 作者:搜寻专家 更新时间:2023-10-31 22:01:15 24 4
gpt4 key购买 nike

官方文档(Swift 4.1)说:

If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values. You also cannot use the implicit self property, or call any of the instance’s methods.

所以我想我需要使用惰性变量,今天我创建了一个按钮

let loginRegisterButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor.rgb(red: 80, green: 101, blue: 161)
button.setTitle("Register", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.addTarget(self , action: #selector(handleRegister), for: .touchUpInside)
return button
}()

所以我只是在 addTarget 方法中使用了 self,而 XCode 似乎并没有打扰更多的程序,没有任何错误。一切都很顺利。那么为什么我在用闭包初始化属性时可以使用 self 呢?是否有一些变化或者我错过了什么?

最佳答案

您代码中的目标是 probably nil,这可能有效的原因是:

...If you specify nil, UIKit searches the responder chain for an object that responds to the specified action message and delivers the message to that object

(来自documentation of the method)

您可以通过在 Controller 初始化期间或之后设置断点并检查 _targetActions 数组(在调试器的变量 View 中)来验证目标实际上是 nil按钮(您可以看到 target 的地址是 0x0)。

在您的示例中,loginRegisterButton 是在 Controller 初始化期间设置的,这意味着还没有 self(换句话说,您不能保证所有实例变量都在这点)。 lazy 解决这个问题的方法是在第一次访问时延迟实际赋值。

关于ios - 为什么我用闭包初始化属性时可以使用 self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50393312/

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