I’ve read http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/BasicViewControllers/BasicViewControllers.html#//apple_ref/doc/uid/TP40007457-CH101-SW19 but I’m still not completely clear on how this works.
@property (nonatomic, retain) UIButton *startButton;
@property (nonatomic, retain) UITextView *infoTextView;
This is a view controller displayed in a tab bar
- (void)loadView
{
UIView *newView = [[UIView alloc] init];
//self.startButton and addSubivew retains the button obect; retain count = 2
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//autorelases
self.startButton = button;
[newView addSubview:startButton];
//addSubview retains infoTextView; self.infoTextview retains; retain count: 2
self.infoTextView = [[[UITextView alloc] initWithFrame:CGRectMake(0.0, 0.0, 280.0, 270.0)] autorelease];
//autoreleased
[newView addSubview:infoTextView];
//View controller retains the view hierarchy
self.view = newView;
[newView release];
}
//customization of the button and textview (text, frame, center, target-action etc)
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadStartButton];
[self loadTextView];
}
//because these have retain properties, they are released through nil
- (void)viewDidUnload
{
self.startButton = nil;
self.infoTextView = nil; //retain counts - 1
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[startButton release];
[infoTextView release]; //retain counts -1
[super dealloc];
}
My question is this: should the UIView objects have retain counts of two? The way I see it is that the view controller retains the UIView object, and the viewController.view also retains the UIView object (through adding subviews). Is this the correct way to look at it conceptually? Because then my viewController is also managing objects owned by its .view property.
However, I’m not sure if both viewDidUnload and dealloc are called in the case of low memory situations. Am I releasing them correctly or setting up a memory leak?
(any comments about putting code in the wrong place would be helpful as well)
In a low-memory situation, I don’t think your view controller will be dealloc’ed. Your view will. viewDidUnload will be called but not dealloc. That’s ok. Your buttons will be freed. Both the reference from the view controller will be released, by your viewDidUnload code, and the reference from addSubview, by the view’s default dealloc code (or somewhere in default code).
When you do deallocate your view controller, if ever, both will get called. The release statements in the dealloc will do nothing, because they will be equivalent to [nil release], which is a no-op. That’s ok.
I think you can take the release statements out of the dealloc though, since dealloc should never get called without viewDidUnload getting called first.