用嵌入SQLite數據庫開發ios應用,我把數據庫放到SQlite管理員,然後拖到Xcode工程中。但是當我打開DB的時候,報錯 out of memory ,不知道是不是SQlite的bug,因為我的文件很小,應該不會報出內存問題。
初始化數據庫的代碼:
- (id)initWithPath:(NSString *)path {
if (self = [super init]) {
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"SoundLib_DB.sqlite"];
if ([fileManager fileExistsAtPath:dbPath] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"SoundLib_DB" ofType:@"sqlite"];
[fileManager copyItemAtPath:resourcePath toPath:dbPath error:&error];
}
success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSLog(@"Cannot locate database file '%@'.", dbPath);
}
sqlite3 *dbConnection;
//Here is when I get the error, at trying to open the DB
if (sqlite3_open_v2("SoundLib", &dbConnection, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK) {
NSLog(@"[SQLITE] Unable to open database!");
NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(database), sqlite3_errcode(database));
return nil;
}
database = dbConnection;
}
return self;
}
報錯可能是由於數據庫路徑傳遞為UTF8String
,我看見你傳遞"SoundLib",不能這樣直接傳遞。
if (sqlite3_open([dbPath UTF8String], &databaseHandle) == SQLITE_OK)
{
//dbPath is your full database path you getting above
}
P.S.dbpath
作為const char
const char *dbpath