Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you initialize property values in a View Controller?

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?

like image 452
El Tea Avatar asked Oct 31 '13 02:10

El Tea


People also ask

How do I initialize a view controller in Swift?

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.

How do you instantiate a view controller in storyboard?

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.


1 Answers

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.

like image 115
Sebastian Avatar answered Sep 18 '22 02:09

Sebastian