Reputation: 4731
When I use xib, -viewDidUnload is called after memory warning.
But when I create view programmatically instead of using xib, -viewDidUnload is not called.
(In both cases, -didReceiveMemoryWarning is called.)
Why -viewDidUnload is not called when I don't use xib file?
Don't I have to write code for -viewDidUnload if I don't use xib?
The followings are the test code and results:
(I'm using ARC)
@implementation ViewControllerA
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = [NSString stringWithFormat:@"%d", gNavigationController.viewControllers.count];
// button to pop view controller to navigation controller
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 100, 200, 50);
[button setTitle:@"push" forState:UIControlStateNormal];
[button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
// button to generate memory warning
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 200, 200, 50);
[button setTitle:@"memory warning" forState:UIControlStateNormal];
[button addTarget:self action:@selector(generateMemoryWarning) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
NSLog(@"view did load %@", self.title);
}
- (void)generateMemoryWarning {
[[UIApplication sharedApplication] performSelector:@selector(_performMemoryWarning)];
}
- (void)push {
UIViewController *viewController = [[ViewControllerA alloc] init];
[gNavigationController pushViewController:viewController animated:YES];
}
- (void)viewDidUnload
{
[super viewDidUnload];
NSLog(@"view did unload %@", self.title);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
NSLog(@"view did receive memory warning %@", self.title);
}
@end
RESULTS
if ViewControllerA doesn't have xib:
view did load 1
view did load 2
view did receive memory warning 1
view did receive memory warning 2
if ViewControllerA has xib:
view did load 1
view did load 2
view did unload 1
view did receive memory warning 1
view did receive memory warning 2
Upvotes: 3
Views: 772
Reputation: 4091
If you are using UIViewContoller
without initializing it from a NIB, you need to subclass the -loadView
method. Otherwise iOS assumes that the view cannot be unloaded / reloaded.
It would be sufficient to just add the following to your implementation:
- (void)loadView {
[super loadView];
self.view = yourCreatedView;
}
Unfortunately the documentation is not very clear on this.
Upvotes: 2