ios - 在两个局部变量之间的仪器中检测到泄漏

标签 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 被正确调用,但是 deinits 来自 ab 实例并未实际调用。

我还说泄漏,因为这实际上在仪器中被检测为泄漏:

enter image description here

现在,如果我将这两个局部变量声明为场景的属性,那么 Instruments 检测到的泄漏会有所不同:

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来自ab 实例没有被调用(因为强引用循环)。

不过,这在 Instruments 中被检测为泄漏...那么对此的合理解释是什么?

最佳答案

我无法使用下面的代码复制它。临时场景已正确取消初始化,并且 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
    }
}

关于ios - 在两个局部变量之间的仪器中检测到泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36184207/

相关文章:

iphone - 在 UIActionSheet 中,iPhone 没有显示取消按钮?

arrays - 搜索值数组以在字典中查找键

ios - 如何快速触发动画序列

c++ - 为什么这个简单的 libpqxx 代码会泄漏内存?

delphi - 从 FastMM 获取更长的堆栈跟踪?

ios - 同时播放多个音频流

ios - 从 UIScrollView Swift 禁用水平滚动

ios - Parse 不允许我为同一用户注册创建 4 行信息

ios - 是init吗?(aDecoder :) or prepareForSegue(_:sender:) called first?

java - Spring内存使用率过高