问题描述
我问这个问题,因为viewDidLoad看起来在初始化程序的主程序块之前被调用,而在初始化程序中初始化的类变量在viewDidLoad中为零。为了您的参考,我以编程方式对整个viewcontroller进行编程,我已经创建了一个自定义的初始化程序,因此我可以使用我的viewcontroller中使用的各种参数。当然,我的自定义初始化程序调用UIViewControllers指定的初始化程序。
基本上,我好奇的是,将参数发送到UIViewController的正确设计模式是什么?我已经阅读过其他线程,并没有真正得到一个确定的答案。我应该跳过初始化程序并手动设置属性(从类外)?好像有些ble h ble,p p p p p p??????????????????????p p p p p p p p p p p p p p p p p p p p p p >在初始化完成之前调用viewDidLoad的原因可能是因为您在初始化程序中调用了view方法。例如:
- (id)init
{
if((self = [super init] )){
_thing = 123;
_other = self.view.frame.size.width / 2;
}
return self;
}
viewDidLoad
被调用视图加载时。一旦您调用视图
方法(或访问视图属性,如果您愿意),视图将加载。所以你应该避免引用init中的视图。
为了回答你的问题,我更喜欢为视图控制器创建一个init方法。
- (id)initWithThing:(MyThing *)thing thang:(MyThang *)thang
{
if((self = [super init])){
_thing = [thing retain];
_thang = [thang retain];
// ...
}
return self;
}
您还可以使用属性在初始化后设置额外的变量。个人而言,我宁愿仅使用可选属性来执行此操作,并在init方法中放入必需的属性。这样我无法启动无效状态的视图控制器。
I ask this question because it appears that viewDidLoad gets called before the main block of the initializer does and the class variables I'm initializing in the initializer are turning up nil in viewDidLoad. For your reference, I'm doing this entire viewcontroller programmatically and I've created a custom initializer so I can take in various parameters to be used in my viewcontroller. My custom initializer calls UIViewControllers designated initializer of course.
Basically, I'm curious about what is the proper design pattern for sending in parameters to a UIViewController? I've read other threads about this and haven't really gotten a definitive answer. Should I just skip the initializer and set the properties manually (from outside the class)? That seems kind of bleh, I'd really like to send in some parameters and am curious how others go about doing this?
The reason viewDidLoad is called before initialization completes, is probably because you call the view method in the initializer. For example:
- (id)init
{
if ((self = [super init])) {
_thing = 123;
_other = self.view.frame.size.width / 2;
}
return self;
}
viewDidLoad
is called when the view loads. And the view loads as soon as you call the view
method (or access the view property, if you prefer). So you should avoid referencing the view in init.
To answer your question, I prefer to create an init method for my view controllers.
- (id)initWithThing:(MyThing *)thing thang:(MyThang *)thang
{
if ((self = [super init])) {
_thing = [thing retain];
_thang = [thang retain];
// ...
}
return self;
}
You can also use properties to set extra variables after initing. Personally I prefer to do this with optional properties only, though, and put required properties in the init method. That way I can't init the view controller with an invalid state.
这篇关于向UIViewController发送参数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!