Skip to content

Instantly share code, notes, and snippets.

Created August 7, 2011 07:09
Show Gist options
  • Save anonymous/1130149 to your computer and use it in GitHub Desktop.
Save anonymous/1130149 to your computer and use it in GitHub Desktop.
Database.m
#import "Database.h"
@implementation Database
static Database *db = nil;
static sqlite3 *_database = nil;
#pragma mark -
#pragma mark Singleton methods
+(Database *) sharedDatabase {
@synchronized(self)
{
if (db == nil)
db = [[Database alloc] init];
}
return db;
}
+(id) allocWithZone:(NSZone *)zone {
@synchronized (self) {
if (db == nil) {
return [super allocWithZone:zone];
}
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone{
return self;
}
#pragma mark -
#pragma mark Private Methods
// Returns a reference to the database.
sqlite3 *Pc2MacDatabase() {
if (_database == nil) {
// First, test for existence.
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:kDatabaseFile];
if ([fileManager fileExistsAtPath:writableDBPath] == NO) {
// Database file doesnt exists. Copy the database at writable path (documents directory).
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kDatabaseFile];
[fileManager removeItemAtPath:writableDBPath error:nil];
BOOL databaseCopied = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!databaseCopied) {
// Handle the error...
}
}else {
// Open the database. The database was prepared outside the application.
if (sqlite3_open([writableDBPath UTF8String], &_database) != SQLITE_OK) {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(_database);
_database = nil;
// Additional error handling, as appropriate...
}
}
}
return _database;
}
#pragma mark -
#pragma mark Closing database
// Close the database. This should be called when the application terminates.
void ClosePc2MacDatabase() {
if (_database == nil) return;
// Close the database.
if (sqlite3_close(_database) != SQLITE_OK) {
// Handle the error...
}
_database = nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment