Question

I read somewhere that in a programmatically created view in a UIViewController, not using Interface Builder, -viewDidLoad and -viewDidUnload should not be used. Is this right? Why? Where would I release subviews that I have retaining properties of? Or should I just not use properties for them?

EDIT: Read my comments on Rob Napier's answer.

Was it helpful?

Solution

Create your subviews in -viewDidLoad. If you need ivars for them then only assign their values. The reference is hold by adding the views as subviews to you main view.

Then when your view is unloaded you should set your ivars to nil, because the object have been released since your view was removed and released.

So in your header

@interface MyViewController : UIViewController {
  IBOutlet UIView *someSubview; // assigned
}
@property (nonatomic, assign) IBOutlet UIView someSubview;
@end

And in your implementation

@implementation MyViewController
//... some important stuff

- (void)viewDidLoad;
{
  [super viewDidLoad];
  someSubview = [[UIView alloc] initWithFrame:self.view.bounds];
  [self.view addSubview:someSubview]; // retains someSubview
  [someSubview release];   // we don't hold it
}

- (void)viewDidUnload;
{
  [super viewDidUnload];
  someSubview = nil;  // set the pointer to nil because someSubview has been released
}

//... more important stuff

@end

If you wish you can also not release someSubview in -viewDidLoad, but then you have to release it in -viewDidUnload AND -dealloc since (if I remember right) -viewDidUnload isn't called before -dealloc. But this isn't necessary if you don't retain someSubview.

OTHER TIPS

the strange thing here is that an UIViewController not loaded from a NIB file is not notified about its view unloading (and so its viewDidUnload method is not called) unless you offer a base implementation of the loadView method, such as:

- (void)loadView {
   self.view = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds] autorelease];
   [self.view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
}

- (void)viewDidLoad {
   [super viewDidLoad];
   // create views...
}


- (void)viewDidUnload {
   // destroy views...
   [super viewDidUnload];
}

this only happens to base UIViewController, an UITableViewController for example don't need to be fixed with this workaroud.

So Robs is right.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top