[英]What is the most correct way to add a UIViewController to a subview and remove it?
我试图添加一个UIViewController子视图,然后单击按钮将其关闭。 我当前的代码可以完成任务,但是我不确定它是否会泄漏或引起任何问题。
所以首先我添加子视图
-(IBAction)openNewView:(id)sender{
// start animation
[UIView beginAnimations:@"CurlUp" context:nil];
[UIView setAnimationDuration:.3];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
// add the view
newViewController* newVC = [[newViewController alloc] initWithNibName:@"newViewController" bundle:[NSBundle mainBundle]];
[self.view addSubview:newVC.view];
[UIView commitAnimations];
}
然后在newViewController.m中,我有删除它的功能
-(IBAction)closeNewView:(id)sender{
// start animation
[UIView beginAnimations:@"curldown" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:.3];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view.superview cache:YES];
// close dialog
[self.view removeFromSuperview];
[UIView commitAnimations];
[self.view release];
}
就像我说的那样有效,但是当我分析代码时,它告诉我:
X线上分配并存储到“ newViewController”中的对象的潜在泄漏:
newViewController* newVC = [[newViewController alloc] initWithNibName:@"newViewController" bundle:[NSBundle mainBundle]];
和
[self.view release];
的调用者此时未拥有的对象的引用计数的错误减少[self.view release];
如果我autorelease
viewController而不是[self.view release]
self.view [self.view release]
它会在删除时崩溃(如果我在添加视图后也释放了视图),则使用以下命令会崩溃:-[FirstViewController performSelector:withObject:withObject:]:消息发送到已释放实例0xd21c7e0
如果我叫[newVC release]
在任一viewControllers dealloc
它未能建立。
希望我不会问一个明显的问题,但是添加和删除viewControllers的正确方法是什么?
您正在使用哪个IOS版本? 如果您使用的是5.0,则应该继续使用ARC,这样就不必自己处理[release]调用。
如果您仍然希望或需要坚持手动进行内存管理:尝试释放newVC时无法创建dealloc的原因是因为该指针的作用域为openNewView函数。 使其成为班级成员,就可以释放它。
@implementation WhateverItsCalled {
newViewController *newVC;
}
- ( IBAction ) openNewView: (id)sender {
...
newVC = [ [ newViewController alloc ] initWithNibNamed:...
}
- ( void ) dealloc {
[ newVC release ];
}
是的,如果您不使用ARC,则每个“分配”都必须与相应的“发行版”配对。
我还必须问-为什么在这里全部使用视图控制器? 如果只需要视图,则可以使用[[NSBundle mainBundle] loadNibNamed]从NIB加载视图,并将[self]列为文件的所有者。 这将设置您的所有引用(包括所需的视图),并且您不必实例化(看起来像)一个多余的视图控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.