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:
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.(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?
Open ImageViewController. swift and add an initializer with name init(coder:image:) . The initializer accepts an NSCoder instance as its first argument and an Image object as its second argument.
In the Storyboard, select the view controller that you want to instantiate in code. Make sure the yellow circle is highlighted, and click on the Identity Inspector. Set the custom class as well as the field called "Storyboard ID". You can use the class name as the Storyboard ID.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With