"Empty Database.m/h template for sqllite3"

Mon 11 May 2009

//

//  Database.h


#import <Foundation/Foundation.h>

#import <sqlite3.h>


@interface Database : NSObject {

sqlite3 *database;

NSString *dbPath;

}

 

+ (Database *)sharedDatabase;

- (void)createEditableCopyOfDatabaseIfNeeded;

- (void) openDb;

@end

 

//-----------------------------------------------------------------------------------------------------

//  Database.m


#import "Database.h"


@implementation Database

 

static Database *_sharedDatabase;

 

BOOL dbOpen = NO;

 

+ (Database *)sharedDatabase

{

if (!_sharedDatabase) {

_sharedDatabase = [[Database alloc] init];

}

return _sharedDatabase;

}

// Creates a writable copy of the bundled default database in the application Documents directory.

- (void)createEditableCopyOfDatabaseIfNeeded {

// First, test for existence.

BOOL success;

NSFileManager *fileManager = [NSFileManager defaultManager];

NSError *error;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"iSearch.sql"];

success = [fileManager fileExistsAtPath:writableDBPath];

if (success) return;

// The writable database does not exist, so copy the default to the appropriate location.

NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"iSearch.sql"];

success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];

if (!success) {

NSLog([error localizedDescription]);

NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);

}

}

 

- (void) openDb {

while (dbOpen) {

//Wait untill db will be closed from othrea thread

[NSThread sleepForTimeInterval:1];

NSLog(@"Wait untill db will be closed from other thread");

}

if (!dbOpen) {

[self createEditableCopyOfDatabaseIfNeeded];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"iSearch.sql"];

//NSLog(path);

//dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database.sql"];

if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {

dbOpen = YES;

}

}

}

 

- (void) closeDb {

if (dbOpen) {

sqlite3_close(database);

dbOpen = NO;

}

}

- (NSString *) getRowString:(char *)inputStr{

if(inputStr == nil)

return @"";

else

return [NSString stringWithUTF8String:inputStr];

}

@end