Follow @endyourif rss Facebook LinkedIn

iPhone Apps Randomly Crashing? iPhone Apps Randomly Crashing?

Published on Feb 4, 2010

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.

Onoccasion, 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!

Tags: iPhone | objective c | iPhone

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP