OStack程序员社区-中国程序员成长平台

标题: iphone - 在文档目录中复制数据库有问题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 11:34
标题: iphone - 在文档目录中复制数据库有问题

我有一个应用程序,我需要将我的数据库文件复制到文档目录。我知道该怎么做,而且效果很好。这是它的代码

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

// 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] stringByAppendingPathComponentataBaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
// Add Skip Backup attribute here.

这工作正常,但由于某些原因有时会产生错误。现在的问题是,当我尝试跟踪此问题时,它不会发生。

我不知道为什么,但 success = [fileManager fileExistsAtPath:writableDBPath]; 返回 NO。比它尝试写入新文件但写入新文件也会失败。 error 很难追踪,因为它在我的测试中没有重现。

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

谢谢



Best Answer-推荐答案


试试下面的代码

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
    }

关于iphone - 在文档目录中复制数据库有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953892/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4