iPhone Apps Randomly Crashing? iPhone Apps Randomly Crashing?

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.:


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

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.


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

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!

Published on Feb 4, 2010

Tags: iPhone | objective c | iPhone

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.