Search code examples
iphonecrashexc-bad-accesssubviewsuperview

removeFromSuperview causes my app to crash


I'm sure this is some stupid mistake, but i'm trying for the past hour to remove a subview from my superview without any success.

On my first view i'm having

UIViewController *helpView = [[[UIViewController alloc] initWithNibName:@"HelpView" bundle:nil] autorelease];
[self.view addSubview:helpView.view];

And then inside helpView i have a button which is connected to an IBAction called "closeHelp" which just does the following:

- (IBAction) closeHelp{
    [self.view removeFromSuperview];
}

But this causes my app to crash with EXC_BAS_ACCESS for some weird reason, even those this is inside the HelpView, meaning self.view should be pointed to the correct subview..

Would appreciate your help

Thank you.
Shai.


Solution

  • As Andreas answered, you are trying to remove self.view from its super/parent view. You basically need to remove the helpView from its parent view.

    so it should be

    - (IBAction) closeHelp{
        [helpView removeFromSuperview];
    }
    

    But we dont know what is "helpView" in the above method. As we dont have any handle for it.

    So our code should finally look like this.

    #define HELP_VIEW_TAG 101 // Give tag of your choice
    
    HelpView *helpView = [[HelpView alloc] initWithNibName:@"HelpView" bundle:nil];
    helpView.view.tag = HELP_VIEW_TAG;
    [self.view addSubview:helpView.view];
    [helpView release];
    
    - (IBAction) closeHelp{
        UIView *helpView = [self.view viewWithTag:HELP_VIEW_TAG];
        [helpView removeFromSuperview];
    }