【问题标题】:iOS ARC UIAlertView leaking memoryiOS ARC UIAlertView 内存泄漏
【发布时间】:2017-10-03 13:46:25
【问题描述】:

我有一个简单的方法来显示带有文本字段的 AlertView。仪器显示内存泄漏。请解释一下。

- (void)method {
NSString *value = [[NSUserDefaults standardUserDefaults] valueForKey:@"key"];
if (value == nil) {

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title" message:@"message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

    alertView.tag = 101;
    alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *txtGroup = [alertView textFieldAtIndex:0];
    [txtGroup becomeFirstResponder];

    [alertView show];
    alertView = nil;
}
}

请查看 Instruments 的截图:

【问题讨论】:

  • 你为什么要让 alertView = nil ?展示后?
  • 我在某处读到,释放一个需要在使用后设置为 nil 的对象。
  • 是的。同意,但是当您显示警报视图时,意味着它仍然在层次结构中,并且您将立即使其为零。在 ARC 中,它会处理它。想做的话,用完后再做
  • 如何从层次结构中删除它并释放(dealloc)它?什么时候?

标签: ios memory-leaks automatic-ref-counting uialertview instruments


【解决方案1】:

您需要将 alertView 创建为:

static UIAlertView *alertView = nil;

if (!alertView){
   alertView = [[UIAlertView alloc] initWithTitle:@"Title" message:@"message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
}

【讨论】:

  • 为什么 UIAlertView 应该是静态的?
  • 因为当你调用这个方法然后alertview创建新的实例所以。
  • 你可以声明 global alertiview 而不是 static 。
  • 为什么会有泄漏,我想知道?还有,怎么去掉?
猜你喜欢
  • 2013-08-19
  • 2012-04-03
  • 2012-09-14
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 2012-08-15
相关资源
最近更新 更多