Where do you initialize property values in a View Controller?

半城伤御伤魂 提交于 2019-12-01 02:09:15

问题


I have a view controller with properties that determine its behaviour. These are set by its parent in prepareForSegue.

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:

  • Set the default values for properties in the child view's viewDidLoad method. However, on investigation, viewDidLoad is called after prepareForSegue 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!

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.

Are there any opportunities for initializing value in the child view controller before prepareForSegue in the parent?


回答1:


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.

On researching, I now understand that properties in Objective C don't have default values.

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.



来源:https://stackoverflow.com/questions/19697410/where-do-you-initialize-property-values-in-a-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!