发现个问题,在初始化时属性的didSet方法不被调用,这样就无法实现一些功能,下面来说一下如何解决这个问题。
应用场景:
structNumber {
var value:Double = 0
}
classtestClass:NSObject{
var str :String = "abc"{
didSet{
print("This is didSet")
}
willSet{
print("This is willSet")
}
}
override init() {
super.init()
print("enter testClass!!")
//应该赋值完成时调用didSet方法
str ="123"
print("curStr =\(str)")
}
}
testClass.init()
完成init方法并赋值完成后,只打印出"enter testClass!!”,然而didSet方法并没有调用
寻找解决方案:
查阅官方文档给出的答案:
在初始化的时候赋值,是不调用didSet方法的。
官方文档没有给出答案,只能另寻方法
解决方案:
但是在有些情况下迫切希望在初始化的时候调用didSet方法,那么可以采用KVC方式给对象初始化,通过KVC方法赋值后,必须添加setValueforUndefinedKey方法做特殊处理,否则运行到KVC方法时程序会报错
上方法:
classtestClass:NSObject{
var str :String = "abc"{
didSet{
print("This is didSet")
}
willSet{
print("This is willSet")
}
}
override init() {
super.init()
print("enter testClass!!")
//应该赋值完成时调用didSet方法
// str = "123"
//通过KVC方法赋值,这里key只需填任意值, 必须添加setValueforUndefinedKey方法做特殊处理
self.setValue("123", forKey: "abc123")
print("curStr =\(str)")
}
//调用KVC的方法key值错误后调用
override func setValue(_value:Any?, forUndefinedKey key:String) {
//重新使用value赋值给str属性就可以成功调用didSet方法
guard let newStr = valueas?String else{
return
}
str = newStr
}
}
testClass.init()
通过调试得出结果:
通过控制台的打印可以看到调用了didSet方法,在didSet方法里做你想做的事情吧,如果帮到了你或者给你提供了一些思路,给个小心心哟😊
网友评论