Reputation: 305
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
Xcode Version 9.4.1 (9F2000)
Upvotes: 0
Views: 427
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:
Upvotes: 0
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