Search code examples
iphoneviewcrashreleasealloc

App crashes when releasing a view properly


Hope you can help me with this problem. I am having issues with the following code:

-(IBAction)swapViews:(id)sender{
    myappAppDelegate *delegate = (myappAppDelegate *) [[UIApplication sharedApplication] delegate];
    ThirdViewController *thirdView = [[ThirdViewController alloc] initWithNibName:@"ThirdViewController" bundle:nil];
    [delegate switchView:self.view toView:thirdView.view];
    [thirdView release];
}

As you can see I allocated my ViewController and released it afterwards. The problem is that when i change views to my ThirdViewController and then want to get back to the previous view, the app crashes. This is how i get back to my previous view:

-(IBAction)goBack:(id)sender{
    myappAppDelegate *delegate = (myappAppDelegate *) [[UIApplication sharedApplication] delegate];
    FirstViewController *firstView = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
    [delegate switchView2:self.view toView:firstView.view];
    [firstView release];
}

Again the same problem when releasing the View. If I don't release the views the app won't crash but there are lots of memory leaks and taking into account I have over 15 ViewControllers, the app will eventually crash if I use it for a long time.

Any ideas what am I doing wrong? ps: I am using a delegate for the animation/transition of the view.

Thanks!

Edit: switchView:toView: code below

-(void)switchView:(UIView *)view1 toView:(UIView *)view2 {
    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:0.75];
    [UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.window cache:YES];
    [view1 removeFromSuperview];
    [window addSubview:view2];
    [UIView commitAnimations];

}


Solution

  • Don't want to sound like Mr. Obvious, but unless the view switched to is being retained in your delegate before its controller is released, you're operating on a released view before switching back, hence the crash.

    It would be probably better if your switchView:toView methods operated on UIViewControllers, not just UIViews. Then you can retain the viewController whose view you need, and release it when it's not needed any more.

    But for now that's all we can take from your current problem description. Show the code of switchView:toView: and switchView2:toView: methods, and the crash log and we'll go from there.