内存泄漏潜力;不能使用UIViewController自动释放

时间:2011-09-11 15:00:30

标签: iphone objective-c memory-leaks clang

我不能让静态分析器'喜欢'这个代码,但同时我不能自动释放存储到控制器中的对象,所以它对调用者来说是无用的。使用这两种静态方法,我试图让它更容易在任何视图上显示活动控制器(不会阻塞选项卡)。

PZActivityOverlayController *view = [PZActivityOverlayController displayOverView:self.view];
// Later on, when complete
[PZActivityOverlayController remove:view];

原始代码:

+ (PZActivityOverlayController *)displayOverView:(UIView *)aView {
  PZActivityOverlayController *controller = [[PZActivityOverlayController alloc] initWithFrame:aView.superview.bounds labelText:@"Loading"];
  [controller viewWillAppear:YES];
  [aView.superview insertSubview:controller.view aboveSubview:aView];
  return controller; // Potential leak of object stored into controller
}

+ (void)remove:(PZActivityOverlayController *)display {
  [display viewWillDisappear:YES];
  [display.view removeFromSuperview];
  [display release]; // However it won't leak because it gets released here
 }

也许我的责任链在这里错了,但这只是为了方便。另一种选择是在任何地方写出这些方法的主体内容(这对我来说太过于干扰)。

1 个答案:

答案 0 :(得分:2)

有一个规则(比如,约定) - 非自动释放的对象由方法alloc& init ...,new,retain,copy返回。所有其他方法都必须返回自动释放的对象。

在你的情况下,我会重写上面的代码:

....
    return [controller autorelease];
}

+ (void)remove:(PZActivityOverlayController *)display {
    [display viewWillDisappear:YES];
    [display.view removeFromSuperview];
}

...

PZActivityOverlayController *view = [[PZActivityOverlayController displayOverView:self.view] retain];
// Later on, when complete
[PZActivityOverlayController remove:view];

[view release];