• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

iphone - 在文档目录中复制数据库有问题

[复制链接]
菜鸟教程小白 发表于 2022-12-12 11:34:58 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

// 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap