iPhone Apps Randomly Crashing?

i

Today at work I was advancing one of our iPhone applications.  It’s a pretty basic application, has a menu which displays some data from the web via XML; all of that fun stuff.

On occasion, I would try to push a view controller and the application would randomly crash, e.g.:

[code]
-(void) showMainMenu {
[mainNavigationController pushViewController:mainMenuViewController animated:YES];
}
[/code]

This would work fine the first few times, then all of a sudden the app would start crashing.  Using the debugger I knew that it must have been a memory issue and that the mainMenuViewController was no longer accessible because the iPhone must have run out of memory and removed to free up space.

I started analyzing my code and best practices and realized that I was not properly allocating and releasing the view controllers from memory.

E.g. in my app delegate controller I had created global variables for my view controllers, set them as properties and then synthesized them at the top of my app delegate.

In the application did load function, I would then allocate them for use throughout the application.

As I stated, this worked fine, but as I pushed and popped the same controllers multiple times, things stopped working properly.

To resolve this issue, I decided that if I don’t need access to the controller throughout my app delegate, there is no reason to make it a global variable.

I now had to go back and remove the variable from the synthesize, property in the header, and a global variable also in the header.  I then copied my allocate call into the function where I pushed that particular view controller.

[code]
-(void) showMainMenu {
MainMenuViewController *mainMenuViewController = [[MainMenuViewController alloc] init];
[mainNavigationController pushViewController:mainMenuViewController animated:YES];
[mainMenuViewController release];
}
[/code]

That is my newly updated showMainMenu function.  Now each time that I call this function, it will not already be in memory and it will be created, pushed, then released freeing up the memory right away.

I know that from now on, I will be doing this at the start of the application and not the end!  I had to spend hours today converting my code to this format!

Other useful articles

About the author

By Jamie

My Books