加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift3 – FileManager replaceItemAt()导致EXC_BAD_ACCESS

发布时间:2020-12-14 04:34:29 所属栏目:百科 来源:网络整理
导读:我写了一个从网站下载图像的应用程序. 如果设备上已存在此图像,我正在尝试更换它. func urlSession(_ session: URLSession,downloadTask: URLSessionDownloadTask,didFinishDownloadingTo location: URL) { let userId = Int.init(downloadTask.taskDescript
我写了一个从网站下载图像的应用程序.
如果设备上已存在此图像,我正在尝试更换它.

func urlSession(_ session: URLSession,downloadTask: URLSessionDownloadTask,didFinishDownloadingTo location: URL) {
    let userId = Int.init(downloadTask.taskDescription!)! // task description is definetly set in downloadImage() and is an Int
    guard let target = imageFolder?.appendingPathComponent("(userId).jpg") else {
        delegate?.imageDownloadFailed(forUser: userId,error: "Could not create target URL.")
        return
    }

    do {
        if fileManager.fileExists(atPath: target.path) {
            _ = try fileManager.replaceItemAt(target,withItemAt: location)
        } else {
            try fileManager.moveItem(at: location,to: target)
        }
        delegate?.savedImage(forUser: userId,at: target)
    } catch let error {
        delegate?.imageDownloadFailed(forUser: userId,error: error.localizedDescription)
    }
}

问题发生在if语句中:

_ = try fileManager.replaceItemAt(target,withItemAt: location)

我总是得到EXC_BAD_ACCESS,我找不到错误.
fileManager,target和location都是非零的.
我已经尝试将代码同步调度到主线程,但错误仍然存??在.

有什么建议吗?

编辑:

由于我不是唯一一个遇到此错误的人,所以我决定在Apple创建一个错误报告.
该报告可在Open Radar获得; click

我还上传了一个playground file at pastebin.com,它演示了错误并提供了类似于naudec的快速解决方案.

解决方法

有同样的问题.写完我自己的版本:

let fileManager = FileManager.default

func copyItem(at srcURL: URL,to dstURL: URL) {
    do {
        try fileManager.copyItem(at: srcURL,to: dstURL)
    } catch let error as NSError {
        if error.code == NSFileWriteFileExistsError {
            print("File exists. Trying to replace")
            replaceItem(at: dstURL,with: srcURL)
        }
    }
}

func replaceItem(at dstURL: URL,with srcURL: URL) {
    do {
        try fileManager.removeItem(at: dstURL)
        copyItem(at: srcURL,to: dstURL)
    } catch let error as NSError {
        print(error.localizedDescription)
    }
}

我先调用copyItem.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读