Keep your iPhone apps from crashing

Yes, once again I found myself having to track down some memory issues. Today I tracked down 3 major areas that cause apps to crash. Yes, even if you do all the great Objective-C alloc/release/dealloc you still will be faced with these.

I think most apps have at least 1 of these 3 potential issues so I'm writing down what I did to mitigate the issues and keep the apps from crashing.

So here are the 3, in the order of memory consumption:

SQLite - no, there is no memory leak in sqlite, but most people keep one opening connection throughout the app and as you keep creating and freeing prepare statements, it continues to use to memory until the database connection is closed.

The Photo Picker - yes, you thought Apple have fixed it in 3.0. They did, but it's still leaking! If your app takes one or two pictures, then it's fine. But if your app allows users to potentially take 100 pictures, then eventually you run out of memory, and crash.

Network connection. NSURLConnection to be specific. Now-a-days most apps are network enabled and connects to the backend. Some people on the web says the leak is minimal so there's no need to worry about. Well, if your app (like games) ping the server every second, then a 100 byte leak will soon add up.

And here are my solutions:

  1. To deal with SQLite, you have two options. One is to open and close connections frequently. Depends on where you grow up, you may or may not like this option. I happened to grow up in Oracle land, so creating connection every time is something that I tend not to do. What I did is to force temp tables to be created in files instead of memory, thus reducing consumption. Just add the following line after opening a database connection:
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK){
sqlite3_exec(database, "PRAGMA temp_store=1", NULL, NULL, NULL); 
//Force using disk for temp storage to reduce memeory footprint.

2. Now the Photo Picker that we all learn to love to hate. The easiest work around is to create a singleton class to limit the memory leak. Basically avoid creating multiple Photo Picker (As everytime you create one, it leaks like 3K).

@interface ZCImagePicker : UIImagePickerController {}
(ZCImagePicker*)sharedInstance;
@end
static ZCImagePicker *myInstance = nil;
@implementation ZCImagePicker
(ZCImagePicker *)sharedInstance {
@synchronized(self) {
if (myInstance == nil) {
myInstance = [[self alloc] init];
}
}
return myInstance;
}
(void)dealloc{
[super dealloc];
}
@end


3. Finally on NSURLConnection, just avoid using sendSynchronousRequest. Use the standard async methods you will be fine.

Hope this can help to keep your next iphone apps from crashing.