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.
You can use a "destructor" to automatically close the database on quit
__attribute__((destructor))
static void close_db (void) {
sqlite3_close(database);
}
精彩评论