开发者

Calling sqlite3_close for a static sqlite3* handle

开发者 https://www.devze.com 2022-12-21 14:46 出处:网络
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:

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消