Graphics Programs Reference
In-Depth Information
Because a view controller's view can be destroyed and reloaded, you need to take some
precautions when writing code that initializes a view controller. Let's do something wrong
to see the potential problem.
In
TimeViewController.m
, set the background color of
TimeViewController
's
view
in
initWithNibName:bundle:
.
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
self = [super initWithNibName:@"TimeViewController"
bundle:[NSBundle mainBundle]];
if (self) {
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:@"Time"];
UIImage *i = [UIImage imageNamed:@"Time.png"];
[tbi setImage:i];
[[self view] setBackgroundColor:[UIColor greenColor]];
}
return self;
}
Build and run the application. The first thing you will notice is that the console reports
that
HypnosisViewController
immediately loads its
view
. Switch to the
Time
tab,
and note that the background color is green. Then switch back to the
Hypnosis
tab and
simulate a memory warning.
Now switch back to the
Time
tab, and you'll see that the background color is no longer
green. The view controller reloaded its
view
, but the view controller's initializer was not
called again. So, the line of code that set the background color of its
view
to green was
not executed, and the view in question was not configured correctly when the view was
reloaded.
This is an important lesson: while you can do initial set-up for a view controller in
initWithNibName:bundle:
, you should never access a view controller's
view
or
any view in its view hierarchy in that method. Instead,
viewDidLoad
is where you
should put any extra set-up messages you wish to send to a view controller's
view
or any
of its subviews.
In
TimeViewController.m
, move the line of code that changes the background color
from
initWithNibName:bundle:
to
viewDidLoad
.
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
self = [super initWithNibName:@"TimeViewController"
bundle:[NSBundle mainBundle]];
if (self) {