【问题标题】:Calling sqlite3_close for a static sqlite3* handle为静态 sqlite3* 句柄调用 sqlite3_close
【发布时间】:2010-02-24 16:46:30
【问题描述】:

我想在 Objective C 中提供对一个 sqlite 数据库的访问。我不想让调用者为数据库本身而烦恼,所以我打算在我的 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。它当然看起来并不优雅。我该如何改进?

一种方法是在每次访问时打开和关闭我的数据库,并摆脱静态数据库句柄。费用是多少?

PS:我没有很强的OO背景,所以如果我的想法不好,我不介意完全改变它。

【问题讨论】:

    标签: objective-c sqlite


    【解决方案1】:

    您可以使用“析构函数”在退出时自动关闭数据库

    __attribute__((destructor))
    static void close_db (void) {
       sqlite3_close(database);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-20
      • 2015-02-14
      • 1970-01-01
      • 2023-02-09
      • 2017-12-08
      • 2013-12-13
      • 2018-09-01
      • 2018-01-13
      相关资源
      最近更新 更多