Where to set a property in UIViewController

ios, objective-c, properties, uiview, uiviewcontroller

Solution

Yeah, you are pretty much right already. The thing is, all views components of your controller are not loaded until the view is actually presented. So you cannot set anything of your IBOutlets from outside the controller.

One approach for passing, for example, a text for an UILabel, it's create a new string property, let's say `self.myString`, assign it from outside, and in your viewDidLoad, set in the labels' text this property.

CustomViewController *controller = [CustomViewController alloc] initWithNibName:nil bundle:nil];
controller.myString = @"label text goes here";

And inside the `CustomViewController`:

- (void)viewDidLoad
{
    [super viewDidLoad];

    (...)
    self.label.text = self.myString;
}

Problem

A rather basic question I'm unsure about. I typically set up my `UIViewController`'s view-related code in `viewDidLoad`. If the controller has some properties for labels, etc, this is where I would initialize them and add them to the view. These properties are usually declared in the .m so can be considered pseudo-private. However - if the controller exposes one of these properties (let's say a `UILabel`) in its header file, I am finding that I can't rely on it existing when it comes time to set it up. For example: ``` CustomViewController *controller = [CustomViewController alloc] initWithNibName:nil bundle:nil]; controller.someLabel.text = @"label text goes here"; //then comes the presentation code ``` I find that I am setting the label's text too early - `viewDidLoad` has not fired yet so the label is nil. Should I create this label in `init` and add it in `viewDidLoad`? Should I be doing all my set up in `init`? Or maybe all the initialization of view properties? Or judge it on a case by case basis? Or maybe the root cause is that I shouldn't have a controller exposing a view (the label) and use some other pattern? I'm looking for a consistent way to structure my code.

Original source