0

.sqlite3 ファイルを iOS にコピーしFMDBてアクセスすると、データベースが空になるようです。Xcodeにドラッグアンドドロップするだけです。私が実行すると:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite3"];
FMDatabase *db = [FMDatabase databaseWithPath:writableDBPath];

FMResultSet *results = [db executeQuery:@"SELECT * FROM tableName"];

resultsnil を返します。を見る[db lastErrorMessage]と、テーブルが存在しないと表示されます。コマンド ラインで .sqlite ファイル (iPhone シミュレーターに格納されているファイル) を開くと、空のデータベースが表示されます。SQLite データベースを iOS にインポートする特定の方法はありますか? もしそうなら、どのように?

4

2 に答える 2

1

考えられる問題が 2 つあります。

まず、.sqlite ファイルがプロジェクト ターゲットに含まれていることを確認します。ファイルナビゲーターでファイルを選択します。[ユーティリティ] パネル ([表示] セクションの右側のパネル アイコン) を開き、[ターゲット メンバーシップ] というタイトルのセクションを探します。目的のターゲット (おそらく 1 つしかない) のボックスがチェックされていない場合、データベース ファイルはバンドルにコピーされていません。

次に、ドキュメント ディレクトリでデータベースを検索しようとしています。ただし、書き込み可能なファイルとして開く前に、バンドルからそのディレクトリに手動でコピーする必要があります。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite3"];

NSURL *dbURL = [NSURL fileURLWithPath:dbPath];

// copy a database from the bundle if not present
// on disk
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:dbPath]) {
    NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"db" withExtension:@"sqlite3"];
    NSError *error = nil;
    if (!bundlePath || ![fm copyItemAtURL:bundlePath toURL:dbURL error:&error]) {
        NSLog(@"error copying database from bundle: %@", error);
    }
}
于 2013-04-07T01:00:28.620 に答える