在removeFromSuperview崩溃应用程序后释放UIView

时间:2012-10-10 12:12:33

标签: iphone objective-c ios ipad memory-management

我有一个UIView对象,我使用[self.view addSubview:mySubView];将其添加为子视图。然后我打电话 [mySubView removeFromSuperview];然后我尝试[mySubView release];,但应用程序崩溃了。

RemoveFromSuperview是否也在release上致电mySubView

3 个答案:

答案 0 :(得分:4)

是的,removeFromSuperview会释放视图。

您查看了文档吗?大概需要5秒钟:

  

<强>讨论
  如果接收者的超级视图不是nil,则超级视图会释放接收者。如果您打算重复使用某个视图,请务必在调用此方法之前retain,然后在适当的时候再次使用release

答案 1 :(得分:3)

是的,超级视图会保留其所有子视图,因此当您删除视图时,其超级视图会将其释放。

答案 2 :(得分:2)

请发布您的代码,否则很难回答

崩溃代码

UIView *subview = [[UIView alloc] init]; //manual allocation
[self.view addSubView:subview]; //view retained automatically
[subview release]; //released the manual allocated memory

for(UIView *subview in [scrollView subviews]) {    

    [subview removeFromSuperview]; //released the view retained automatically. Now retain count reach 0/
   [subview release]; // crash.....
}

无崩溃的代码

UIView *subview = [[UIView alloc] init]; //manual allocation
[self.view addSubView:subview]; //view retained automatically   

[subview removeFromSuperview]; //released the view retained automatically. Now retain count reach 1

[subview release]; // No crash .retain count reach 0

您根本不会发布自己未明确分配或保留的内容。

相关问题