[英]viewDidLoad not called when initialising obj viewcontroller from Swift
In my Swift code, I am trying to instantiate an Objective-C view controller like below, however the viewDidLoad
method is not being called.在我的 Swift 代码中,我试图实例化一个如下所示的 Objective-C 视图控制器,但是没有调用
viewDidLoad
方法。
let detailMessageVC = DetailMessageViewController(nibName:nil, bundle:nil)
If I instantiate the same viewcontroller from Objective-C code like this it does get called.如果我像这样从 Objective-C 代码实例化相同的视图控制器,它确实会被调用。 There is no xib for the view controller.
视图控制器没有xib。
self.detailMVC = [[DetailMessageViewController alloc] init];
Does anyone know why this is happening?有谁知道为什么会这样? I would like to have the same behaviour when calling from Swift as I rely on the
viewDidLoad
to perform various initialisation.我希望在从 Swift 调用时具有相同的行为,因为我依赖
viewDidLoad
来执行各种初始化。 This is with Xcode 6.3.2这是 Xcode 6.3.2
As comment stated, there is no link between initialisation of a view controller and it's viewDidLoad
callback.正如评论所述,视图控制器的初始化与其
viewDidLoad
回调之间没有联系。
You can even have viewDidLoad
called before init.您甚至可以在 init 之前调用
viewDidLoad
。 Because viewDidLoad
is called if the ViewController effectively loaded a view.因为如果 ViewController 有效地加载了一个视图,就会调用
viewDidLoad
。
Check there : https://stackoverflow.com/a/4862772/1486230检查那里: https : //stackoverflow.com/a/4862772/1486230
Although, I wouldn't rely on viewDidLoad
unless you know that you will effectively display your ViewController;虽然,除非您知道将有效地显示您的 ViewController,否则我不会依赖
viewDidLoad
; Mostly by using myVC.view
.主要是通过使用
myVC.view
。
Just think like initialising a ViewController (which is only a logic object) is different than creating its view.试想一下,初始化一个 ViewController(它只是一个逻辑对象)与创建它的视图是不同的。 For performance reason, iOS won't create the graphic object if they are not needed.
出于性能原因,如果不需要,iOS 不会创建图形对象。 If you get a difference between Swift and Objective-C, it's more because Swift is probably better on optimisation.
如果您对 Swift 和 Objective-C 有所不同,那更多是因为 Swift 在优化方面可能更好。 But the behaviour is normal.
但行为是正常的。
对于 iOS 9+,您可以调用vc.loadViewIfNeeded()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.