Graphics Programs Reference
In-Depth Information
When TimeViewController recreates its view , it will create a new instance of
UILabel and set its timeLabel instance variable to point to it. At this point, the old
label will be destroyed. But we shouldn't wait on TimeViewController to reload its
view to fix this memory leak. We can't be sure when or even if that will happen.
After a view controller's view is unloaded during a memory warning, the view controller
is sent the message viewDidUnload . You override this method to get rid of any strong
references to subviews of the view controller's view . In TimeViewController.m ,
override viewDidUnload .
- (void)viewDidUnload
{
[super viewDidUnload];
NSLog(@"Unloading TimeViewController's subviews");
timeLabel = nil;
}
Build and run this application. Tap on the Time tab and then go back to the Hypnosis tab.
Simulate a memory warning and note the log message in the console. Notice that if you
simulate a memory warning while TimeViewController 's view is visible, you will
not see this message - a view is only unloaded if it is not on the screen.
Overriding viewDidUnload is one way to fix this problem, but we can solve it more
simply with weak references. If you specify that timeLabel is a weak reference, then
the view would keep the only strong reference to the UILabel , and when the view was
destroyed, the UILabel would be destroyed, and timeLabel would automatically be
set to nil .
Figure 7.18 TimeViewController before and after memory warning (with weak ref-
erence)
Search WWH ::




Custom Search