从iOS 4 SDK上的SuperView中删除视图

时间:2011-10-08 09:13:05

标签: iphone navigation views

我正在使用iOS 4 SDK开发iPhone 3.1.3应用程序。

我有两个ViewControllers,mainViewController和AboutViewController。

我使用此代码从mainViewController转到AboutViewController(mainViewController.m中的代码):

- (IBAction) aboutClicked:(id)sender
{
    AboutViewController* aboutController =
        [[AboutViewController alloc] 
         initWithNibName:@"AboutViewController"
                  bundle:nil];
    [self.view addSubview:aboutController.view];

    [aboutController release];    
}

这是从AboutViewController返回到mainViewController(AboutViewController.m中的代码):

- (IBAction) backClicked:(id) sender
{
    [self.view removeFromSuperview];
}

当我点击AboutViewController上的Back Button时,我得到一个EXC_BAD_ACCESS。

我正在使用基于窗口的应用程序模板。

我还尝试在[self.view removeFromSuperview]中添加断点,但我不能。

你知道为什么吗?

4 个答案:

答案 0 :(得分:1)

请改为:

- (IBAction) aboutClicked:(id)sender
{
    AboutViewController* aboutController =
        [[AboutViewController alloc] 
         initWithNibName:@"AboutViewController"
                  bundle:nil];
    [self presentModalViewController:aboutController animated:YES];

    [aboutController release];    
}

这是从AboutViewController返回到mainViewController(AboutViewController.m中的代码):

- (IBAction) backClicked:(id) sender
{
    [[self parentViewController] dismissModalViewControllerAnimated:YES]
}

答案 1 :(得分:0)

尝试:

[self presentModalViewController:aboutController animated:YES];

展示视图并:

[self dismissModalViewControllerAnimated:YES];

删除视图...

答案 2 :(得分:0)

1)使aboutController成为一个类级变量

2)创建一个委托方法来处理

(IBAction) backClicked:(id) sender

3)执行委托调用

 [aboutController.view removeFromSuperView];

答案 3 :(得分:0)

你得到EXC_BAD_ACCESS的原因是因为在将viewController的视图添加为子视图后释放了控制器,因此触摸事件无法看到预期的viewController来处理它。

注释掉下面的发布声明,它应该可以正常工作

- (IBAction) aboutClicked:(id)sender
{
    AboutViewController* aboutController =
    [[AboutViewController alloc] 
     initWithNibName:@"AboutViewController"
              bundle:nil];
    [self.view addSubview:aboutController.view];

//[aboutController release]; To avoid leaking consider creating aboutController variable at instance level and releasing it in the dealloc.
}