I was reading retain cycle and tried the following code which should in theory leak memory but when I use Instruments, it does not show any memory leaks
import UIKit
class ViewController: UIViewController {
private var button = {
let _button = UIButton()
_button.setTitle("Tap Me", for: .normal)
_button.setTitleColor(.systemBlue, for: .normal)
return _button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(button)
button.addTarget(self, action: #selector(actionButton), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
button.widthAnchor.constraint(equalToConstant: 80),
button.heightAnchor.constraint(equalToConstant: 30)
])
}
@objc private func actionButton() {
let secondVC = ViewController2()
present(secondVC, animated: true)
}
}
class MyView: UIView {
let viewContoller: ViewController2
init(from vc: ViewController2) {
viewContoller = vc
super.init(frame: .zero)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController2: UIViewController {
var myView: MyView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
myView = MyView(from: self)
}
}
There’s a button on ViewController
which upon tapping opens a new view controller ViewController2
which initialises a UIView
and hence should create a retain cycle (since the view also holds ViewController2 object). Where exactly am I going wrong?