views:

1579

answers:

2

At the beginning of my app, I am initializing a UIViewController with a NIB.

At some point, I am removing the view from the screen, then releasing it, so it no longer takes up memory. (At this point I am also saving the state of the view in the UIViewController)

At a later point, I want to recreate the view and bring it back on screen. I will then restore it's state. (Using the same UIViewController, not a new one, since it saved the state)

My question, is when I recreate the view, how do I do so from the NIB, or is this not possible?

To me, the obvious remedies are:

  1. Don't save state in the UIViewcontroller (Where does convention dictate that I do save state?)

  2. Don't release the view (maybe just release all of it's subviews?)

  3. Don't load my view from a NIB, create programatically (seems to go against using IB for everything)

Note: I am not using a UINavigationController, I am handling the swapping of the views myself, since thee are only 2 of them.

+2  A: 

If you need that level of control, you dont really want to use IB. Because, as you noted, if remove the view and then later recreate it, you would have to do it in code then anyway. Just design most of the views in IB, then write some code that generates just this view. Then you can call that same method again later to recreate that view when you need it.

You may be able to archive it and later turn it back into an object, but that seems like an inelgant solution. IB does not allow for dynamic creation of controls at runtime, even if they used to exist but don't anymore. There is no shame in leaving IB out of loop for this. In fact it's probably a good idea.


OR

If its a complicated view with a lot of pieces, put the view in it's own nib, and make a view controller for it. Then you can simply instatiate the view controller with the nib name, and add the controllers view as a subview to you main view. Then your view controller handles loading of the nib, and you get to design it in IB. Nothing says the view of a view controller has to take up the entire screen either.

self.otherController = [[OtherController alloc] initWithNibName:@"Other" bundle:nil];
[self.view addSubview:otherController.view];
Squeegy
A: 

Don't create the view controller and the view in the same nib file; either create the controller in code or put the view in a separate nib file. If you later nil out your controller's view property, the controller should recreate the view.

But why are you so worried about this? There's already a mechanism to automatically free up the view if you're low on memory: the low memory warning. It will only destroy and recreate the view if you actually need to do so, and it's built in to the system so you don't have to do anything. Remember the saying about premature optimization?

Brent Royal-Gordon