2011-11-08 23 views
0

データベースをNSBundleからドキュメントディレクトリにコピーしたいとします。NSBundleからドキュメントディレクトリにファイルをコピーできません

これは、ファイルをコピーするためのコードです:

- (NSString *) getDBPath 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    return [documentsDir stringByAppendingString:@"Mydata.sqlite"]; 
} 

- (void) copyDatabaseIfNeeded 
{ 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSString *dbPath = [self getDBPath]; 
    BOOL success = [fileManager fileExistsAtPath:dbPath]; 

    if(!success) { 

    NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Mydata.sqlite"]; 
    success = [fileManager copyItemAtPath:defaultPath toPath:dbPath error:&error]; 

    if (!success) 
     NSAssert1(0, @"Failed to create writable file with message '%@'.", [error localizedDescription]); 
    } 
} 

をしかし、なぜ、それは私が私のiPadでこのアプリケーションを実行すると、それがクラッシュするということでしょうか?

+0

エラーメッセージは何ですか? – Nekto

+0

私はそれがクラッシュする理由を見つけました! 問題はここにあります。return [documentsDir stringByAppendingString:@ "Mydata.sqlite"]; 代わりにstringByAppendingPathComponentを使用する必要があります。 – Lloydworth

答えて

0

チェックこの行私はあなたが私のアドバイスは、起動時にDB「移動」を管理することですコアデータを使用している場合、これは間違ったパス

+0

ああ、私は悪いです。私は質問を掲示している間に間違いを犯しました。はい私はそれを "Mydata.sqlite"に変更しましたが、それでもクラッシュします。 – Lloydworth

+0

sqlite extensionを使用してファイルを作成しました。 –

0

だと思う

NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Photo.png"]; 

。 コアデータスタック管理を使用してください(組み込みテプレートから無料で入手できます)。

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 

    if (persistentStoreCoordinator_ != nil) { 
     return persistentStoreCoordinator_; 
    } 

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"MyData.sqlite"]; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if (![fileManager fileExistsAtPath:storePath]) { 
     NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"MyData" ofType:@"sqlite"]; 
     if (defaultStorePath) { 
      [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL]; 
     } 
    } 

    NSURL *storeURL = [NSURL fileURLWithPath:storePath]; 

    NSError *error = nil; 
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    }  

    return persistentStoreCoordinator_; 
} 

- (NSString *)applicationDocumentsDirectory { 
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
} 

データを管理するときは、必ずこのコードを使用します。

関連する問題