美文网首页
Swift中,在初始化时didSet不被调用或无效的解决方法

Swift中,在初始化时didSet不被调用或无效的解决方法

作者: XAKX | 来源:发表于2017-03-28 11:21 被阅读0次

应用场景:

structNumber {

varvalue:Double= 0

}

classtestClass:NSObject{

varstr :String="abc"{

didSet{

print("This is didSet")

}

willSet{

print("This is willSet")

}

}

overrideinit() {

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{

varstr :String="abc"{

didSet{

print("This is didSet")

}

willSet{

print("This is willSet")

}

}

overrideinit() {

super.init()

print("enter testClass!!")

//应该赋值完成时调用didSet方法

//        str = "123"

//通过KVC方法赋值,这里key只需填任意值, 必须添加setValueforUndefinedKey方法做特殊处理

self.setValue("123", forKey:"abc123")

print("curStr =\(str)")

}

//调用KVC的方法key值错误后调用

overridefuncsetValue(_value:Any?, forUndefinedKey key:String) {

//重新使用value赋值给str属性就可以成功调用didSet方法

guardletnewStr = valueas?Stringelse{

return

}

str= newStr

}

}

testClass.init()

通过调试得出结果:

通过控制台的打印可以看出,didSet方法

相关文章

网友评论

      本文标题:Swift中,在初始化时didSet不被调用或无效的解决方法

      本文链接:https://www.haomeiwen.com/subject/tkhjottx.html