sqlite データベースを開きたい場合は、次のようにします。
バンドルにデータベースが含まれていることを確認してください。
バンドルからドキュメントにデータベースをプログラムでコピーします (ユーザーがデータベースを変更する場合は特に重要です。読み取りのみを行う場合は、バンドル内のバージョンを開くだけで済みます)。
これをシミュレーターで実行している場合は、バンドルとドキュメント フォルダーを検査して、問題が解決しない場合は、すべてが正しい場所にあることを確認してください。シミュレーターのフォルダーは、「~/Library/Application Support/iPhone Simulator/5.1/Applications/」のようなものです (5.1 は、使用しているシミュレーターのバージョンに置き換えてください)。コマンド ライン ウィンドウchflags nohidden ~/Library
でを実行して、Library フォルダーを再表示する必要がある場合があります。Terminal
したがって、データベースのパスを取得するためのコード (および、ドキュメントがまだ存在しない場合はそれをドキュメントにコピーするためのコード) は、次のようになります。
NSString *databaseName = kDatabaseName; // obviously, replace this with your database filename, e.g., @"myExampleDatabase.db"
NSString *documentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *databaseFullDocumentPath = [documentsFolder stringByAppendingPathComponent:databaseName];
NSString *databaseFullBundlePath = [[NSBundle mainBundle] pathForResource:databaseName ofType:@""];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:databaseFullDocumentPath])
{
NSAssert([fileManager fileExistsAtPath:databaseFullBundlePath], @"Database not found in bundle");
NSError *error;
if (![fileManager copyItemAtPath:databaseFullBundlePath toPath:databaseFullDocumentPath error:&error])
NSLog(@"Unable to copy database from '%@' to '%@': error = %@", databaseFullBundlePath, databaseFullDocumentPath, error);
}
次に、独自の sqlite 呼び出しを行う場合は、次のようになります。
sqlite3 *database;
if (sqlite3_open_v2([databaseFullDocumentPath UTF8String], &database, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
{
// do whatever you want to do
}
あるいは、FMDB を使用している場合は、次のようになります。
FMDatabase *db = [[FMDatabase alloc] initWithPath:databaseFullDocumentPath];
NSAssert(db, @"Unable to open create FMDatabase");
BOOL success = [db open];
NSAssert(success, @"Unable to open database");
if (success)
{
// do whatever you want to do
}