对象层次结构导致Swift中的内存泄漏 [英] Object hierarchy is causing a memory leak in Swift

查看:129
本文介绍了对象层次结构导致Swift中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够提炼我在我编写的应用程序中看到的问题,并在一个简单的例子中复制了它。



鉴于这些类:

  class Thing {
var name:String =
var price:Double = 0.0
var更改:Double = 0.0
var percentChanged:Double = 0.0
}

class TestUIViewController:UIViewController {

}

class ViewController:TestUIViewController {

var thing:Thing?

@IBAction func clicked(_ sender:AnyObject){
self.thing = Thing()
}

}

我用按钮创建了一个UIView,当按下时,会实例化一个东西。使用Instruments分析器,我可以看到发生内存泄漏。



但是,如果ViewController类从UIViewController扩展,则没有问题。



这一切都是从一个快速测试应用程序转载而来的,因此我无法想到其他外部力量。



这里是示例代码 -



这是预期的结果。有9个瞬态东西,只有一个持久的东西 - 目前分配给该属性的东西。如果有多个持久性Thing就会出现泄漏,而且没有。



此外,这就是Xcode中内存规格的样子:





我们有点上升(一种台面 )当我反复点击按钮时,我们再次回到基准水平。


Ive been able to distill a problem seen in an app I've written, and have reproduced it in a simple example.

Given these classes:

class Thing {
    var name:String = ""
    var price:Double = 0.0
    var changed:Double = 0.0
    var percentChanged:Double = 0.0
}

class TestUIViewController: UIViewController {

}

class ViewController: TestUIViewController {

    var thing:Thing?

    @IBAction func clicked(_ sender: AnyObject) {
        self.thing = Thing()
    }

}

I created a UIView with a button, that when pressed, a thing is instantiated. With the Instruments profiler up, I can see memory leaks occurring.

However, if the ViewController class extends from UIViewController, there are no issues.

This was all reproduced from a quick test app, so there are no other external forces at play here that i can think of.

Here is the example code - https://www.dropbox.com/s/ooqh77lhpzbvpv1/ArcTest.zip?dl=0

解决方案

You may have found a bug in the leak detector, and it could be quite an interesting bug, so you should report it to Apple. But there is in fact no leak. I downloaded and ran your project under Instruments and clicked the button 10 times. This is what I saw in Instruments allocations template:

That is the expected result. There are 9 transient Things, and only one persistent Thing — the one currently assigned to the property. A leak would be if there were more than one persistent Thing, and there isn't.

Also, this is what the memory gauge looks like in Xcode:

We get a little rise (a kind of "mesa") when I repeatedly tap the button, but then we settle back down to the base level again.

这篇关于对象层次结构导致Swift中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆