Search code examples
iphonememory-managementuiviewcontrollerviewdidload

iPhone dev - viewDidLoad and viewDidUnload in programmatically created view?


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.


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.