Either there is something weird in my project (Mojave, XCode10) or I am missing something very basic.
This is my whole code:
import Foundation
import Cocoa
class ViewController: NSViewController {
public init () {
super.init(nibName: nil, bundle: nil)
self.view = ConfigView(rect: NSRect(x: 0, y: 0, width: 400, height: 300))
print("2")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
print("3")
}
override func viewDidLoad() {
super.viewDidLoad()
print("4")
}
override func viewWillAppear() {
super.viewWillAppear()
print("5")
}
override func viewDidAppear() {
super.viewDidAppear()
print("6")
print("Is loaded: \(isViewLoaded)")
}
}
class ConfigView: NSView {
public init(rect: NSRect) {
super.init(frame: rect)
print("1")
}
required public init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I want to setup stuff in the viewDidLoad()
method, but this method is never called. The console shows:
1 2 5 6 Is loaded: true
So, obviously loadView()
and viewDidLoad()
are not called, but afterwards when the view appeared isViewLoaded()
shows true.
Why is that lifecycle method being ignored?
CodePudding user response:
I suspect what is happening here is that since you are initializing the view
property in the init
function, when loadView()
is called, it detects that the view has already been loaded and therefore does not call the viewDidLoad()
.
Have you tried putting the view instantiation into the loadView()
function instead of the init
? In any case, I would not recommend creating the view in the init
function.
CodePudding user response:
If you implement loadView
, you must not call super
. And you must make a view and assign it as self.view
. Fix that and all will be well. Of course, in real life, you would never implement loadView
, so all this is academic.