在文档目录中复制数据库存在问题

时间:2013-06-06 04:52:33

标签: iphone ios nsfilemanager nsdocumentdirectory

我有一个应用程序,我需要将我的数据库文件复制到文档目录。我知道如何做到这一点并且运作良好。这是它的代码

// 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,因为它在我的测试中没有再现。

今天能告诉我由于这种情况发生的可能错误并提供解决方案。

由于

1 个答案:

答案 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
    }