views:

105

answers:

1

I want to provide access an sqlite database in Objective C. I don't want the caller to bother about the DB itself and so I intend to do something like this in my DataStore.m:

#import "DataStore.h"
#import <sqlite3.h>

static sqlite3 *database = nil;

@implementation DataStore

+ (void) initialize {

  if(self != [DataStore class])
    return;

  ...
  ...

  sqlite3_open(databasePath, &database);
}

+ (NSArray *) readWith:foo:bar {
  ...
}

+ (bool) writeWith:foo:bar {
  ..
}

Now the problem with the whole thing is: I will never get to call sqlite3_close throughout the entire application. It certainly does not look elegant. How could I improve this?

One way would be to open and close my database on each access, and get rid of the static DB handle. How costly would it be?

PS: I don't have a strong OO background and so if my idea is bad, I don't mind changing it altogether.

A: 

You can use a "destructor" to automatically close the database on quit

__attribute__((destructor))
static void close_db (void) {
   sqlite3_close(database);
}
KennyTM
Thanks! Worked like a charm.
submachine