【发布时间】:2017-03-10 15:11:22
【问题描述】:
我正在处理一些释放问题,并且可能是无法弄清楚的强引用或循环引用。我有三个UIViews 实例化如下:
有一个主要的ViewController,我在故事板中添加了一个UIView,UIView 在类中有一个weak 出口,例如:
class ViewController : UIViewController {
//MARK: - outlets
@IBOutlet weak var firstView: FirstUiview!
}
第二个UIView 以编程方式作为子视图添加到第一个视图中,例如:
class FirstUiview : UIView {
//creating an instance of secondUiView
lazy var mySecondView: SecondViewClass = {
let dv = SecondViewClass()
dv.backgroundColor = UIColor.red
return dv
}()
//sometime later by clicking on a button
self.addSubview(mySecondView)
//a button will be tapped to remove mySecondView;
//later will be called at some point upon tapping:
func removingSecondViewByTapping() {
if mySecondView.isDescendant(of: self) {
mySecondView.removeFromSuperview()
}
}
}
现在SecondViewClass 是:
class SecondViewClass : UIView {
//in this class I create bunch of uiview objects like below:
lazy var aView : UIView = {
let hl = UIView()
hl.tag = 0
hl.backgroundColor = UIColor.lightGray
return hl
}()
self.addSubview(aView) //... this goes on and I add other similar views the same way.
//creating an instance of thirdView
var let thirdView = UIView()
self.addSubview(thirdView)
}
现在,如果用户点击按钮删除 mySecondView,然后在其他时间再次添加它(仍然在同一个 ViewController 中),我希望 mySecondView 的所有子视图都已被释放并消失,但它们是都在那里。如果有人能指出我在哪里保持强引用或者是否存在循环引用问题,我将不胜感激?或者别的什么?
【问题讨论】:
-
为什么你会期望第二个视图的子视图消失?从其父视图中删除
mySecondView并不会使其从自身中删除其所有子视图。 -
@dan 哦,等等,我以为 view.removeFromSuperview 会释放并销毁包含其子视图的视图,除非它的子视图引用了所持有的东西,不是吗?如果没有,你能不能指导我如何完全删除发送视图,包括它的子视图?
标签: ios swift memory-management weak-references dealloc