开发者

Removing a view from a SuperView on iOS 4 SDK

I'm developing an iPhone 3.1.3 app with iOS 4 SDK.

I have two ViewControllers, mainViewController and AboutViewController.

I use this code to go from mainViewController to AboutViewController (code inside mainViewController.m):

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

    [aboutController release];    
}

And this to come back from AboutViewController to mainViewCon开发者_如何学Pythontroller (code inside AboutViewController.m):

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

When I click on Back Button on AboutViewController, I get an EXC_BAD_ACCESS.

I'm using a window-based application template.

I've also tried to add a breakpoint in [self.view removeFromSuperview] but I can't.

Do you know why?


Do this instead:

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

    [aboutController release];    
}

And this to come back from AboutViewController to mainViewController (code inside AboutViewController.m):

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


The reason why you get EXC_BAD_ACCESS is because after adding the view of a viewController as sub view you released the controller, hence the touch event couldn't see the intended viewController to process it.

comment out the release statement like below and it should work

- (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.
}


Try:

[self presentModalViewController:aboutController animated:YES];

To present the view and:

[self dismissModalViewControllerAnimated:YES];

To remove the view...


1) Make aboutController a class level variable

2) Create a delegate method to handle

(IBAction) backClicked:(id) sender

3) In implementation of delegate call

 [aboutController.view removeFromSuperView];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜