当我设置该属性的属性时,为什么在属性上调用'didset'? [英] Why is 'didset' called on a property when I set the property of that property?
问题描述
在此代码中,当文本更改时,将调用 titleEditingChanged
(按预期方式)。但当它执行行
In this code when the text changes, titleEditingChanged
is called (as expected). But when it executes the line
investment?.title = sender.text!
它调用 didset {}
投资
。
为什么?
it calls the didset{}
of Investment
.
Why?
class InvestmentCell: UITableViewCell {
var investment: Investment? {
didSet {
// setup UI elements from class properties
textField.text = investment?.title
valueField.text = investment?.value?.description
}
}
@IBAction func titleEditingChanged(sender: UITextField) {
investment?.title = sender.text!
}
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var valueField: UITextField!
}
推荐答案
这是因为投资
可能是一个结构,而不是一个类。
在Swift结构中是值类型,而不是作为类的引用类型。
因此,结构不是可变的。
It is called because Investment
is probably a struct, not a class.
In Swift structs are value types, not reference types as classes.
So, structs are not "mutable in place".
这意味着无论何时更改结构属性,都会分配一个新的结构对象来替换当前的结构对象。 ,当前对象数据被复制到新的对象数据,但更改的属性将包含新的值集。
It means that whenever you change a struct property a new struct object is allocated to replace the current one, the current object data is copied to the new one except for the changed property that will contain the new value set.
请记住,编译器不允许您更改结构使用 let
命令初始化struct对象时的属性(使用类可以执行此操作)。
Remember that the compiler does not let you change a struct property whenever you initialize a struct object with a let
command (with a class you can do it).
解释了为什么每次更改struct属性时都会调用观察者。一旦分配了新的struct对象来替换当前的对象,它现在将存储在另一个内存块中,因此它的值将被更改,并且将调用 didSet
observer。
That explains why the observer is called whenever you change a struct property. Once a new struct object is allocated to replace the current one, it will now be stored in another memory block, so its value will be changed and the didSet
observer will be called.
PS:如果您将投资
定义为一个类而不是结构。
PS: It will not happen if you define Investment
as a class instead of a struct.
这篇关于当我设置该属性的属性时,为什么在属性上调用'didset'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!