问题描述
我有一个视图控制器,其属性决定了它的行为。这些是由其父项在 prepareForSegue
中设置的。
I have a view controller with properties that determine its behaviour. These are set by its parent in prepareForSegue
.
这在我的程序中引发的潜在错误是父母在问题不能保证设置属性,所以我想有一个默认值。在研究方面,我现在明白Objective C中的属性没有默认值。这给我留下了以下选项:
The potential bug this induces in my program is that the parent in question is not guaranteed to set the properties, so I would like to have a default value. On researching, I now understand that properties in Objective C don't have default values. This left me with the following options:
- 在子视图的
viewDidLoad $中设置属性的默认值c $ c>方法。但是,在调查中,
viewDidLoad
在父母的prepareForSegue
之后被称为 - 所以我会在父实际设置属性时覆盖父级的值。 - 然后我认为我可以使用
(id)init
来初始化值,但是,至少在使用故事板时,根本不调用此方法!
- Set the default values for properties in the child view's
viewDidLoad
method. However, on investigation,viewDidLoad
is called afterprepareForSegue
in the parent - so I would be overwriting the parent's values when the parent actually does set the properties. - I then thought I could use
(id) init
to initialize the values, but, at least when using storyboards, this method isn't called at all!
我可能有一个解决方法对象将初始化为默认值,但在这种情况下,我要传入的所有内容都是BOOL。并且由于即使没有正确初始化,bool也会有某个值,我无法测试它是否为非零。
I may have a workaround in that objects will initialize to a default value, but in this case all I want to pass in is a BOOL. And since the bool will have some value even if not initialized correctly, I can't test it to see if it is non-nil.
在父级中 prepareForSegue
之前,是否有机会在子视图控制器中初始化值?
Are there any opportunities for initializing value in the child view controller before prepareForSegue
in the parent?
推荐答案
覆盖 init
将无济于事,因为它不是 UIViewController
对象的指定初始化程序。手动实例化视图控制器时 - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
从故事板加载时被调用 - (id)initWithCoder:(NSCoder *)解码器
将被调用。如果要在初始化视图控制器时设置属性,则必须覆盖两个初始化器。
Overriding init
will not help as it is not the designated initialiser for UIViewController
objects. When manually instantiating a view controller - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
is called, when loaded from a storyboard - (id)initWithCoder:(NSCoder *)decoder
will be called. If you want to set properties when the view controller is initialised you have to override both initialisers.
他们这样做。 nil
表示对象, 0
表示整数值, 0.0
表示如果您需要除此之外的默认值,则应在相应的init方法中设置它们。
They do. nil
for objects, 0
for integer values, 0.0
for floating points etc. If you need default values other than that you should set them in the appropriate init method.
这篇关于您在哪里初始化View Controller中的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!