Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
939 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

enter image description here

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:

enter image description here

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...