Title: Calling sqlite3_close for a static sqlite3* handle
Tags: objective-c;sqlite
Question: 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&gt;

static sqlite3 *database = nil;

@implementation DataStore

+ (void) initialize {

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

  ...
  ...

  sqlite3_open(databasePath, &amp;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.


Here is the accepted answer: You can use a "destructor" to automatically close the database on quit

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



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 2.5', 'CreationDate': '2010:00:02/24/10', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<objective-c><sqlite>', 'Title': 'Calling sqlite3_close for a static sqlite3* handle', 'ViewCount': 2119, 'id': 2324046, 'user_AboutMe': '<p>Work History (in reverse chronological order):</p>\n<ul>\n<li>[current] member of the Toolchain team (<a href="https://sourceware.org/git/?p=glibc.git&amp;a=search&amp;h=HEAD&amp;st=author&amp;s=Arjun+Shankar" rel="nofollow noreferrer"><em>glibc</em></a>) at <em>Red Hat, Brno</em></li>\n<li>wrote test automation for glibc at <em>Red Hat, Brno</em></li>\n<li>wrote a <a href="https://repository.tudelft.nl/islandora/object/uuid:49a3bfaa-012f-4e3b-ac34-b8d9a760c4fc" rel="nofollow noreferrer"><em>GCC</em> RTL optimization pass</a> at <em>ST-Ericsson, Eindhoven</em></li>\n<li>studied <em>Computer Engineering</em> at <em>TU, Delft</em></li>\n<li>wrote bits of an <a href="http://en.wikipedia.org/wiki/Message_oriented_middleware" rel="nofollow noreferrer"><em>MOM</em></a> at <em>SAP Labs, Bangalore</em></li>\n<li>spent a few years in the foothills of the <em>Himalayas</em> <br />\n(while studying <em>Electronics</em> at <em>NIT, Hamirpur</em>)</li>\n</ul>\n', 'user_AccountId': 102096.0, 'user_DisplayName': 'ArjunShankar', 'user_Reputation': 22540.0, 'user_Views': 3588.0, 'user_id': 274261.0}}