うまくいけば、これは理にかなっています。ドキュメントフォルダーに sqlite データベースがあります。そのファイルがディレクトリに存在するかどうかを確認する機能もあり、存在しない場合はメインバンドルからそこに移動されます。したがって、データベースがアクセスするのに適切な場所にあることがわかります。ただし、アプリを実行すると、次のエラーが表示されます: no such table: databaseName. 問題は sqlite データベースの読み書きアクセスと関係があるのでしょうか? もしそうなら、これを確認して問題を修正するにはどうすればよいですか?
#define kFilename @"foods.sqlite"
- (NSString *)dataFilePath {
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* sqliteFile = [documentsPath stringByAppendingPathComponent:kFilename];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:sqliteFile];
if(fileExists)
return sqliteFile;
else {
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kFilename];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:kFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath
toPath:folderPath
error:&error];
NSLog(@"Error description-%@ \n", [error localizedDescription]);
NSLog(@"Error reason-%@", [error localizedFailureReason]);
}
return [documentsPath stringByAppendingPathComponent:kFilename];
}
-(void) viewWillAppear:(BOOL)animated{
sqlite3 *database;
if (sqlite3_open([[self dataFilePath] UTF8String], &database)
!= SQLITE_OK) {
sqlite3_close(database);
NSAssert(0, @"Failed to open database");
}
sqlite3_stmt *statement;
//why is this if statement failing?
if (sqlite3_prepare_v2(database, [sqlStatement UTF8String],
-1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
//int row = sqlite3_column_int(statement, 0);
char *rowData = (char *)sqlite3_column_text(statement, 1);
foodName = [[NSString alloc] initWithUTF8String:rowData];
[foodArray addObject:foodName];
}
sqlite3_finalize(statement);
}
else {
NSLog(@"%i", sqlite3_prepare_v2(database, [sqlStatement UTF8String],
-1, &statement, nil));
NSLog(@"Statement: %s", sqlite3_errmsg(database));
}
sqlite3_close(database);
}