Search code examples
iossqliteinitializationcreate-table

IOS/SQLLite: Where/Where is the best time to create the database


I'm currently including my sqllite database into my app and I keep wondering when is the best time in the life cycle of the application to create the tables (or check that they exist).

In most examples I read, the author does something like this:

- (void)viewDidLoad
{
    NSString *docsDir;
    NSArray *dirPaths;

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];

        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";

            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                status.text = @"Failed to create table";
            }

            sqlite3_close(contactDB);

        } else {
            status.text = @"Failed to open/create database";
        }
    }

    [filemgr release];
    [super viewDidLoad];

}

But I keep wandering if the viewDidLoad is the baset place to create it. Could it be better to create during the initialisation of the app ?

This is more a question of what is the best practice rather since my current code works jusst fine ^^

Thanks for your opinions

Jason


Solution

  • The best place to initialize your model is in your app delegate. The iOS Springboard animates your splash screen and displays it until your app delegate's application:didFinishLaunchingWithOptions: returns, allowing you to make blocking operations without the user noticing them too much (no UI stutter). This method is called only once, so you can be sure the database creation code won't be called multiple times during your application's current run.

    The code typically looks like this, give you have a DataModel singleton class that initializes the database when you initialize its instance through the first call to its sharedModel method:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        [DataModel sharedModel];
    
        // Initialize your window and root view controller...
    
        return YES;
    }