Jonesy
Jonesy

Reputation: 305

Memory leak when adding subview

When adding a subview, the view controller seems to leak.

Why does the following print 'What'

import UIKit

final class ViewController: UIViewController {

    private lazy var mySwitch: UISwitch = {
        let mySwitch = UISwitch()
        mySwitch.tintColor = .blue
        return mySwitch
    }()

    func setup() {
        view.addSubview(mySwitch)
    }

    @objc func switchChangedState() {

    }

    deinit {
        print("what")
    }
}

var controller: ViewController? = ViewController()
controller = nil

But the following does not

var controller: ViewController? = ViewController()
controller?.setup()
controller = nil

Edit: adding GIF

enter image description here

Xcode Version 9.4.1 (9F2000)

Upvotes: 0

Views: 427

Answers (2)

Pete Morris
Pete Morris

Reputation: 1562

There's nothing wrong with your code. There's no retain cycle here.

The problem appears to be something to do with the playground. It could be a bug, or the playground may be retaining your view controller for some reason.

If you execute your code in an actual Xcode project (either in the iOS simulator or on a device), the initializer is executed in both cases:

deinit executes in both cases

Upvotes: 0

Yun CHEN
Yun CHEN

Reputation: 6648

Your code is good. controller?.setup() will not cause a leak. Please make sure the code in test case 2 is really called or not. (No calling no "what" printed)

Upvotes: 1

Related Questions