看看我的代码如下,我得到内存错误后,我点击“后退”按钮,这个问题将被修复,如果我删除aboutView版本为什么?我该如何释放aboutView呢?
-(IBAction)swichView {
AboutView *aboutView = [[AboutView alloc] init];
[aboutView.view setAlpha:0];
[self.view addSubview:aboutView.view];
[UIView beginAnimations:@"" context:nil];
[UIView setAnimationDuration:1.0];
[aboutView.view setAlpha:1];
[UIView commitAnimations];
[aboutView release];
}第二视图控制器:
-(IBAction)back {
[UIView beginAnimations:@"" context:nil];
[UIView setAnimationDuration:1.0];
[self.view setAlpha:0];
[UIView commitAnimations];
[self.view removeFromSuperview];
}发布于 2012-04-11 08:57:40
在您的switchView中,不应该创建AboutView的实例。AboutView *aboutView应该创建为实例变量,而不是函数局部变量。
由于视图控制器动画的设计,动画本身不会保留您的控制器并在动画结束时自动释放它。您的代码在动画期间取消分配视图控制器,这就是它会崩溃的原因。
要在动画之后正确释放视图,请尝试:
-(IBAction)switchView {
// given that aboutView is an instance variable
aboutView = [[AboutView alloc] init];
[aboutView.view setAlpha:0];
[self.view addSubview:aboutView.view];
[UIView animationWithDuration:1.0 animations:^{
[aboutView.view setAlpha:1];
} completion:^(BOOL fin) {
// don't release it
}];
}
-(IBAction)back {
[UIView animationWithDuration:1.0 animations:^{
[aboutView.view setAlpha:0];
} completion:^(BOOL fin) {
[aboutView.view removeFromSuperview];
[aboutView release];
}];
}发布于 2012-04-11 10:40:11
问题可能出在-(IBAction)back;中的[self.view removeFromSuperview];
你不需要那个。在UIViewController中,只要您在dealloc中释放它,就会为您处理它的视图。
当您使用addSubview:时,控制器视图将保留AboutView
此方法保留视图,并将其下一个响应者设置为接收者,即其新的superview。--
addSubview:文档
因此,当视图发布时,aboutView也会发布。
发布于 2012-04-11 13:12:57
在方法'-(IBAction)swichView‘之后似乎没有保留aboutView对象
行'self.view addSubview:aboutView.view;‘
将为aboutView.view,提供额外的引用计数,而不是aboutView本身。
我可能会使用类似于UIPopoverViewController工作方式的委托模型。
使用方法定义一个协议,如下所示
-(void) subViewClosed:(AboutView*)aboutView;让父级实现它,然后继续:
父级
-(IBAction)swichView {
.. existing stuff ..
(dont release)
aboutView.delegate = self;
}AboutView类
-(IBAction)back {
... existing stuff ...
[self.delegate subViewClosed:self];
}父级
-(void) subViewClosed:(AboutView*)aboutView{
[aboutView release];
}https://stackoverflow.com/questions/10098410
复制相似问题