【问题标题】:-viewDidUnload is not called after memory warning when xib is not used未使用 xib 时,内存警告后不调用 -viewDidUnload
【发布时间】:2012-09-12 12:25:59
【问题描述】:

当我使用 xib 时,在内存警告后调用 -viewDidUnload。
但是当我以编程方式而不是使用 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

【问题讨论】:

  • 您是否创建视图并在 loadView 中设置 (self.view = myView;)?

标签: iphone ios


【解决方案1】:

如果您使用UIViewContoller 而不从NIB 初始化它,您需要继承-loadView 方法。否则 iOS 假定视图不能被卸载/重新加载。

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

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

很遗憾,documentation 对此不是很清楚。

【讨论】:

  • 感谢您提供非常有帮助的答案!当我添加 -loadView 时调用了 -viewDidUnload。但是如果我不想让 iOS 卸载我的视图,不设置 self.view 好吗?还是应该始终将创建的视图设置为 self.view?
  • 如果你不想让iOS卸载你的View,你不应该设置self.view,但最佳使用(MVC)应该创建一个UIView并将它分配给self.view
  • 次要 nitpick(对不起),loadview 的苹果文档指定“您的此方法的自定义实现不应调用 super。”每developer.apple.com/library/ios/#documentation/uikit/reference/…
猜你喜欢
  • 1970-01-01
  • 2011-07-01
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多