Swift中willSet和didSet不调用
willSet和didSet如果在初始化(init)的方法内写是无效的,但是又需要在初始化的时候调用didSet,那么可以采用KVC的方式给对象初始化,就可以调用willSet&didSet了
override init(frame: CGRect) {
super.init(frame: frame)
setValue(true, forKey: "isConnect")
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
guard let newValue = value as? Bool else {
return
}
isConnect = newValue
}
var isConnect : Bool = false {
didSet {
}
}
本文详细介绍了在Swift中如何在初始化过程中有效调用willSet和didSet观察者属性。通过KVC方式设置初始值,确保属性变化观察在对象创建时得以执行。
1231

被折叠的 条评论
为什么被折叠?



