我只是在玩泄漏并试图故意创造一个。所以,即使做这样的事也是愚蠢的:
class LeakingObjectA{
var strongRefToB:LeakingObjectB?
deinit{ print("LeakingObjectA deinit")}
}
class LeakingObjectB{
var strongRefToA:LeakingObjectA?
deinit{ print("LeakingObjectB deinit")}
}
这对科学目的来说很好,这创造了一个强大的参考周期。
现在在didMoveToView
里面,我声明了局部常量并像这样发生泄漏:
override func didMoveToView(view: SKView) {
let a = LeakingObjectA()
let b = LeakingObjectB()
a.strongRefToB = b
b.strongRefToA = a
}
转换到另一个场景后,场景的deinit
被正确调用,但来自deinits
和a
个实例的b
不是< / strong>实际上被称为。
另外我说泄漏因为这实际上是在仪器中检测到的泄漏:
现在,如果我将这两个本地变量声明为场景属性,那么仪器检测到泄漏之间会有什么区别:
class GameScene:SKScene {
let a = LeakingObjectA()
let b = LeakingObjectB()
//...later in didMoveToView method I make a strong reference cycle like from the example above
}
当然,在这种情况下,过渡后也会调用场景deinit
,同上,deinits
和a
b
实例未被调用(因为强引用周期)。
仍然,这是不检测到仪器泄漏......那么对此有什么合理的解释呢?
答案 0 :(得分:0)
我无法使用下面的代码复制此内容。临时场景被正确地取消初始化,LeakingObjectA
和LeakingObjectB
都出现在泄漏工具中。
class LeakingObjectA {
var strongRefToB:LeakingObjectB?
deinit{ print("LeakingObjectA deinit")}
}
class LeakingObjectB {
var strongRefToA:LeakingObjectA?
deinit{ print("LeakingObjectB deinit")}
}
class TempScene : SKScene {
let a = LeakingObjectA()
let b = LeakingObjectB()
override init() {
a.strongRefToB = b
b.strongRefToA = a
super.init(size: CGSizeZero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
print("Deiniting temp scene")
}
}
class ViewController {
var tempScene: TempScene?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tempScene = TempScene()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
tempScene = nil
}
}