为静态 sqlite3* 句柄调用 sqlite3_close [英] Calling sqlite3_close for a static sqlite3* handle

查看:25
本文介绍了为静态 sqlite3* 句柄调用 sqlite3_close的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Objective C 中提供对 sqlite 数据库的访问.我不希望调用者打扰数据库本身,所以我打算在我的 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 {
  ..
}

现在整个事情的问题是:我永远不会在整个应用程序中调用 sqlite3_close.它看起来当然不优雅.我该如何改进?

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:我没有很强的面向对象背景,所以如果我的想法不好,我不介意完全改变它.

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

这篇关于为静态 sqlite3* 句柄调用 sqlite3_close的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆