2013-06-06 79 views
2

我有一個應用程序,我需要將我的數據庫文件複製到文檔目錄。我知道如何做到這一點,並且運作良好。這裏是它的代碼複製文檔目錄中的數據庫有問題

// Get Required Path 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSError *error; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName]; 

// Check if DB file already Exist. If YES than return. 
success = [fileManager fileExistsAtPath:writableDBPath]; 
if (success) return success; 

// If DB file is not exist try to write file. This will execute first time only. 
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName]; 
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
// Add Skip Backup attribute here. 

這工作正常,但由於某種原因有時會產生錯誤。現在的問題是當我試圖追蹤這個問題時,它不會發生。

我不知道爲什麼,但success = [fileManager fileExistsAtPath:writableDBPath];正在返回NO。它試圖寫入新文件,但寫入新文件也會失敗。它很難追查error,因爲它不是在我的測試中複製。

可以anyboday告訴我由於這種情況可能出現的錯誤,並提供解決方案。

感謝

+0

什麼是錯誤出現? –

+0

這不是我得到它只發生在一個設備,該設備不在我身邊。不在我的設備中發生。 –

回答

1

嘗試用下面的代碼

BOOL copySucceeded = NO; 


    // Get our document path. 
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentPath = [searchPaths objectAtIndex:0]; 

    // Get the full path to our file. 


    NSString *filePath = [documentPath stringByAppendingPathComponent:fileName]; 



    // Get a file manager 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    // Does the database already exist? (If not, copy it from our bundle) 
    if(![fileManager fileExistsAtPath:filePath]) { 

     // Get the bundle location 
     NSString *bundleDBPath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil]; 

     // Copy the DB to our document directory. 
     copySucceeded = [fileManager copyItemAtPath:bundleDBPath 
              toPath:filePath 
               error:nil]; 

     if(!copySucceeded) { 
      //not Copy 
     } 
     else { 
      // Success 
     } 

    } 
    else { 
     // Nothing 
    }