当我使用 xib 时,在内存警告后调用 -viewDidUnload。
但是当我以编程方式创建 View 而不是使用 xib 时,不会调用 -viewDidUnload。

(在这两种情况下,都会调用 -didReceiveMemoryWarning。)

为什么不使用 xib 文件时不调用 -viewDidUnload?
如果我不使用xib,难道我不必为-viewDidUnload 编写代码吗?

以下是测试代码和结果:
(我正在使用 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

结果

如果 ViewControllerA 没有 xib:
view did load 1
view did load 2
view did receive memory warning 1
view did receive memory warning 2

如果 ViewControllerA 有 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

最佳答案

如果您使用 UIViewContoller 而没有从 NIB 初始化它,您需要子类化 -loadView 方法。否则 iOS 假定 View 无法卸载/重新加载。

只需将以下内容添加到您的实现中就足够了:

- (void)loadView {
    [super loadView];
    self.view = yourCreatedView;
}

不幸的是,documentation 对此不是很清楚。

关于iphone - -viewDidUnload 在未使用 xib 时出现内存警告后不调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12388138/

10-12 00:22
查看更多