我正在与UIStackViews
合作,我遇到了一个我自己无法理解的有趣问题。
我认为这只是我在内存管理和地址方面的误解,但如果情况并非如此,我想要一个确认和解释。
我在这里创建了一个项目来展示这个问题: https://github.com/racer1988/UIKitMemoryAddressTest
我创建了一个UILabel
,我将其添加到UIStackView
中,我可以使用指向标签的变量来编辑其值,该视图反映了我的更改。
现在,如果我创建一个新的UILabel
并将其分配给原始指针..出于某种奇怪的原因,我的想法也希望它在视图中替换Label。 < / p>
相反..变量只是开始指向新视图而另一个变量保留在UIStackView
不变。
UIStackView
对其层次结构中的视图有强烈的引用?)
在UIStackView
?中替换复杂视图的最佳方法是什么?
(让我们想象一个非常复杂的视图,其中包含许多不能仅仅作为label.text进行编辑的数据)
我想到的最好方法是:
有一种不那么麻烦的方式吗?
代码:
// Let's Create a Label, and add it to a StackView
theLabel = UILabel()
theLabel.textAlignment = .Center
theLabel.text = "FIRST LABEL"
mainStackView.addArrangedSubview(theLabel)
print(mainStackView.subviews)
// Here the address of the label, in the StackView
// [<UILabel: 0x7fdc32d16150; frame = (0 0; 0 0); text = 'FIRST LABEL'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdc32e56020>>]
// Let's change the text of the label
theLabel.text = "CHANGED FIRST LABEL"
// The UI is of course correctly edited!
print(mainStackView.subviews)
// Address is of course the same, text is of course changed.
// [<UILabel: 0x7fdc32d16150; frame = (0 0; 0 0); text = 'CHANGED FIRST LABEL'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdc32e56020>>]
// HERE HERE!!!
// Let's replace the UILabel with a new one!
// Does this only change the variable as a pointer ???
// Let's see the address of the original label
print(unsafeAddressOf(theLabel))
// 0x00007fdc32d16150
// Let's make a second pointer to the same label
let theLabelPointerCopy = theLabel
// Let's create a new label
theLabel = UILabel()
theLabel.text = "Second Label"
print(unsafeAddressOf(theLabel))
// 0x00007fdc32e5b560
print(unsafeAddressOf(theLabelPointerCopy))
// 0x00007fdc32d16150
// Address has changed, but not for the copy and not in the stackview (makes sense, partially to me)
print(mainStackView.subviews)
// Same as before
// [<UILabel: 0x7fdc32d16150; frame = (0 0; 0 0); text = 'CHANGED FIRST LABEL'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdc32e56020>>]
theLabelPointerCopy.text = "I Can still change what it is in the stackview"