仪器在两个本地变量之间检测到泄漏

时间:2016-03-23 16:53:54

标签: ios swift memory-leaks sprite-kit instruments

我只是在玩泄漏并试图故意创造一个。所以,即使做这样的事也是愚蠢的:

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被正确调用,但来自deinitsa个实例b不是< / strong>实际上被称为。

另外我说泄漏因为这实际上是在仪器中检测到的泄漏:

enter image description here

现在,如果我将这两个本地变量声明为场景属性,那么仪器检测到泄漏之间会有什么区别:

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,同上,deinitsa b实例未被调用(因为强引用周期)。

仍然,这是检测到仪器泄漏......那么对此有什么合理的解释呢?

1 个答案:

答案 0 :(得分:0)

我无法使用下面的代码复制此内容。临时场景被正确地取消初始化,LeakingObjectALeakingObjectB都出现在泄漏工具中。

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
    }
}