lazy var use invalid
Generally speaking, using lazy var in UIViewController ensures that it is created only when it is used for the first time.
However, if you access this View before viewDidLoad(), the View will be created twice, indicating that the Lazy var mechanism has expired. I searched online and said that Lazy var will fail under multi-threading. However, I printed the logs and both creations were in the main thread.
Cause analysis
The reason I guess is that the creation of UIViewController uses some thread acceleration method, which causes some confusion in the method?
Do not access the View inside before viewDidLoad(), otherwise it will cause inexplicably difficult to troubleshoot bugs!
class NoSafeVC: UIViewController { lazy var myView: UIView = { let view = UIView(frame: ) print("create myView \(view) \()") return view }() init() { (nibName: nil, bundle: nil) _ = myView // Visit in advance } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { () = .gray (myView) } }
create myView <UIView: 0x104b19730; frame = (0 0; 375 667); layer = <CALayer: 0x280fd1f40>> <NSThread: 0x281ae08c0>{number = 1, name = main} create myView <UIView: 0x104b198a0; frame = (0 0; 375 667); layer = <CALayer: 0x280fd1fc0>> <NSThread: 0x281ae08c0>{number = 1, name = main}
The above is the detailed content of solving the problem of the failure of iOS Swift Lazy var View. For more information about the failure of iOS Swift Lazy var View, please follow my other related articles!