代码之家  ›  专栏  ›  技术社区  ›  Veeru

iphone xcode;释放一个视图实例,使表与数据源崩溃

  •  0
  • Veeru  · 技术社区  · 14 年前

    当我有一个带有表的视图时,我的代码因访问错误而崩溃。我已经知道问题是什么,但正在寻找正确的解决方案。

    在视图1中-我有一个按钮,用于创建和实例视图2,然后释放它,如下所示:

      settingsScreen *settings = [[settingsScreen alloc] initWithNibName:@"settingsScreen" bundle:nil];
      CGRect theFrame = settings.view.frame;
      //theFrame.origin = CGPointMake(self.view.frame.size.width, 0);
      theFrame.origin = CGPointMake(0,-(self.view.frame.size.height));
      settings.view.frame = theFrame;
      theFrame.origin = CGPointMake(0,0);
      [UIView beginAnimations:nil context:nil]; 
      [UIView setAnimationDuration:0.8f];
      settings.view.frame = theFrame;
      [UIView commitAnimations];
      [self.view addSubview:settings.view];
      [settings release];
    

    在视图2中有一个表,我在其中设置了数据源,并在viewdidload上将其委托给self,但这会使应用程序崩溃,并导致exec_bad_access

    如果我删除了视图1中的[设置释放],一切都很好。

    如果我不释放视图,将其留在内存中是否是错误的?

    我怎样才能克服这种情况?

    谢谢

    2 回复  |  直到 14 年前
        1
  •  0
  •   Sanniv    14 年前

    您应该使用pushviewcontroller或presentmodalview controller,而不是在另一个viewcontroller中添加一个viewcontroller的视图,当您想要返回时,可以使用popviewcontroller或dismissmodalview controller,这也有助于内存管理。在initwithnibname中,也可以使用[nsbundle mainbundle]作为bundle参数,该参数在bundle中找到合适的xib。

    我确信你的设置实例会再次在你的代码中的某个地方发布,这会使你的应用不稳定。

        2
  •  0
  •   Sagar    14 年前

    桑尼夫的回答是正确的。你应该使用推流行的概念 navigation controller 或以模态方式呈现控制器。 (访问:i) http://forums.macrumors.com/showthread.php?t=472236 &(二) http://www.iphonedevsdk.com/forum/iphone-sdk-development/3643-pushviewcontroller-versus-presentmodalviewcontroller.html 更多信息)。

    现在,您得到的错误是因为您的“设置”对象正在动画中使用,您将在动画完成之前释放它。因此,不要立即释放对象,而是使用另一个方法释放,该方法将在动画停止后调用。如下所示:

    settingsScreen *settings = [[settingsScreen alloc] initWithNibName:@"settingsScreen" bundle:nil];
    CGRect theFrame = settings.view.frame;
    //theFrame.origin = CGPointMake(self.view.frame.size.width, 0);
    theFrame.origin = CGPointMake(0,-(self.view.frame.size.height));
    settings.view.frame = theFrame;
    theFrame.origin = CGPointMake(0,0);
    
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.8f];
    [UIView setAnimationDidStopSelector:@selector(releaseObjects)];
    
    settings.view.frame = theFrame;
    [self.view addSubview:settings.view];
    
    [UIView commitAnimations];
    

    在“ReleaseObjects”对象方法中,应该释放设置对象。在某种情况下,如果您的设置对象是本地的,那么它会像这样自动释放吗?-

    settingsScreen *settings = [[[settingsScreen alloc] initWithNibName:@"settingsScreen" bundle:nil] autorelease];