2011-11-08 61 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

檢查此行

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

,我認爲這是錯誤的道路

+0

哦,我的壞。發佈問題時我犯了一個錯誤。是的,我已將它更改爲「Mydata.sqlite」,但它仍然崩潰。 – Lloydworth

+0

你有沒有用sqlite擴展名創建文件。有時候你可能會錯過 –

0

如果您使用的核心數據我的建議是管理DB「移動」在啓動時。 只需使用核心數據堆棧管理(您將從內置的teplate中免費獲得)。

- (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]; 
} 

我總是在我管理數據時使用該代碼。

相關問題