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

任何人都可以告诉我由于发生这种情况而可能出现的错误并提供解决方案。

谢谢

4

1 回答 1

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
    }
于 2013-06-06T05:00:41.923 回答