tags:

views:

15

answers:

1

Hi all, I'm just wondering why when I create a new view controller, I have to push the controller onto the stack before assigning values to its properties? Why, if I assign a value before the push, are the values not sent to the navigation controller as well?

this works:

SomeViewController *newViewController = [[NewViewController alloc]initWith....];
[self.navigationController pushViewcontroller:newViewController animated:YES];
newViewController.property = value;

this doesn't:

SomeViewController *newViewController = [[NewViewController alloc]initWith....];
newViewController.property = value;
[self.navigationController pushViewcontroller:newViewController animated:YES];

Similarly, if my new view controller has a UITextView property, I can't access it as an instance variable until after I've pushed it onto the navigation stack. I would have thought the instance variable would be accessible once I've instantiated the controller?

Thanks for reading!

A: 

Generally speaking, you can set properties before you push a controller. Your second example should work fine (I use that sequence frequently in my own code).

However, if you are dealing with properties that are IBOutlets connected to objects in your nib file, they won't generally be connected immediately. When the view is loaded from the nib (which doesn't happen, generally, until something tries to access the view property of your view controller) the outlets are connected to the newly created UI objects.

That's why you can access the UI properties after you push the view controller. The view is shown immediately, which forces it to be loaded, and then the objects are available to you.

My approach is to store the values I need to display a view in non-IBOutlet properties, which I set before I push the view (or add it to a tab controller, etc). Then I set up the UI objects in -viewDidLoad or -viewWillAppear.

Seamus Campbell
Thanks Seamus, You're correct, the properties I'm using are IBOutlets so I understand why they're not usable until after the view controller has displayed the view.thanks.
Oliver H
I don't *think* there's a guarantee that pushing a view controller loads the view - if you want to force the view to load, call `[newViewController view]` explicitly. In general, though, avoid stuff which requires the view to be loaded, as it's likely to break on a memory warning.
tc.