简体   繁体   中英

Object hierarchy is causing a memory leak in Swift

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM