UINavigationController crash because of pushing and poping UIViewControllers

Posted by Wayne Lo on Stack Overflow See other posts from Stack Overflow or by Wayne Lo
Published on 2010-05-11T00:16:48Z Indexed on 2010/05/11 0:24 UTC
Read the original article Hit count: 613

My question is related to my discovery of a reason for UINavigationController to crash. So I will tell you about the discovery first. Please bare with me.

The issue: I have a UINavigationController as as subview of UIWindow, a rootViewController class and a custom MyViewController class. The following steps will get a Exc_Bad_Access, 100% reproducible.:

[myNaviationController pushViewController:myViewController_1stInstance animated:YES];
[myNaviationController pushViewController:myViewController_2ndInstance animated:YES];

Hit the left back tapBarItem twice (pop out two of the myViewController instances) to show the rootViewController.

After a painful 1/2 day of try and error, I finally figure out the answer but also raise a question. The Solutio: I declared many objects in the .m file as a lazy way of declaring private variables to avoid cluttering the .h file. For instance,

#impoart "MyViewController.h"
NSMutableString*variable1;

@implement ...

-(id)init
{
   ...
   varialbe1=[[NSMutableString alloc] init];
   ...
}

-(void)dealloc
{
   [variable1 release];
}

For some reasons, the iphone OS may loose track of these "lazy private" variables memory allocation when myViewController_1stInstance's view is unloaded (but still in the navigation controller's stacks) after loading the view of myViewController_2ndInstance. The first time to tap the back tapBarItem is ok since myViewController_2ndInstance'view is still loaded. But the 2nd tap on the back tapBarItem gave me hell because it tried to dealloc the 2nd instance. Executing [variable release] resulted in Exc_Bad_Access because it pointed randomly (loose pointer).

To fix this problem is simple, declare variable1 as a @private in the .h file.

Here is my Question: I have been using the "lazy private" variables for quite some time without any issues until they are involved in UINavigationController. Is this a bug in iPhone OS? Or there is a fundamental misunderstanding on my part about Objective C? Please help.

© Stack Overflow or respective owner

Related posts about uinavigationcontroller

Related posts about crash