开发者

UiViewController - Pop doesn't pop

I'm displaying UIControllerView subclass when a button is pressed from a another UIViewController like this:

- (IBAction)openNextLevelViewController
{
    NSLog(@"openNextlevelViewController");

    [self.navigationController pushViewController:nextLevelViewController animated:YES];

}

And the app will return from that view on a button push which trigger this method:

-(IBAction) returnToStart {

    NSLog(@"returnToStart method called");
    [self.navigationController popViewControllerAnimated:YES];

}

The problem is that the displayed view not getting destroyed/deallocated on the pop. As a result, when it gets pushed, it's not executing the viewDidLoad, which initiates some variables. This may be causing a related problem where, the second time through, when the user presses the return button, the "pop" no longer causes a return to the 开发者_如何学Pythonprevious controller.

What's the best way to deal with this? I could move the initialization code to the "willAppear" method, but it seems as if that could be called almost randomly.


Well, its not getting released because nextLevelViewController is still being retained somewhere else. Most likely in your nextLevelViewController variable.

- (IBAction)openNextLevelViewController
{
    NSLog(@"openNextlevelViewController");
    // assuming you have nib already set up
    UIViewController *nextLevelViewController = [[NextLevelViewController alloc] init]; 
    // RETAIN COUNT = 1

    // navigationController retains your controller
    [self.navigationController pushViewController:nextLevelViewController animated:YES]; 
    // RETAIN COUNT = 2

    // Don't need it any more let navigation controller handle it.
    [nextLevelViewController release]
    // RETAIN COUNT = 1 (by NavigationController)
}

Further On

-(IBAction) returnToStart {
    [self.navigationController popViewControllerAnimated:YES];
    // RETAIN COUNT = 0, dealloc will be called on your viewController, make sure to release all your retained objects.
}

Now when your controller gets popped, it SHOULD get released (shouldn't have been retained anywhere else). And next time you call openNExtLevelViewController, it'll be initializing a new instance of your viewController anyway.

I'm a fan of releasing viewController when it is no longer needed (displayed), instead of holding it in memory. Let navigationController and TabBarController handle viewControllers whenever possible.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜