1

アプリケーションの起動時に、Documents ディレクトリに DB が存在するかどうかを確認します。そうでない場合は、メイン バンドルにある DB をアプリの Documents ディレクトリにコピーします。

非常に簡単に思えますが、シミュレーターでコードを実行した場合にのみ、ココア エラー コード 4 が表示されます。cocoa エラー コードは、ファイルが存在しないことを意味します。コードのこの時点で Documents ディレクトリが存在しない可能性が最も高いということです。

これが私のコードです:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:@"app.db"];

if([[NSFileManager defaultManager] fileExistsAtPath:appDBPath]) {
    //PERFORM DATA MIGRATIONS IF ANY EXIST
}
else {
    NSString *appDBBundlePath = [[NSBundle mainBundle] pathForResource:@"app" ofType:@"db"];
    NSError *error;
    if(![[NSFileManager defaultManager] copyItemAtPath:appDBBundlePath toPath:appDBPath error:&error]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:[error localizedDescription]
                                                       delegate:nil
                                              cancelButtonTitle:@"ok"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

アプリがインストールされると、Documents ディレクトリが存在するといつも思っていました。私は何を間違っていますか?注: 物理デバイス上のアプリを使用して、バンドルからドキュメント ディレクトリに DB をコピーできます。

4

0 に答える 0