ios - 对于 in 循环结果有时在 EXC_BAD_ACCESS

标签 ios swift exc-bad-access

有时我会在这段代码中遇到 EXC_BAD_ACCESS 错误:

internal func downloadMultiple(files: NSMutableArray, remoteBaseUrl: NSURL, completion: (result: Int)->()) -> Void {
    self.filesToDownload = files
    self.cb = completion

    for item in files { // this line gets marked, but why this line?
        print("file ", item["file"] as! String)
        self.download(remoteBaseUrl.URLByAppendingPathComponent(item["file"] as! String)!)
    }
}

但它只是偶尔发生,知道如何找出造成这种情况的原因吗?

最佳答案

你遇到崩溃是因为 item[file]nil 并且你正在使用强制展开,像这样使用可选绑定(bind)

for item in files { 
    // this line gets marked, but why this line?
    if let file = item["file"] as String {
        print("file ", file)
        self.download(remoteBaseUrl.URLByAppendingPathComponent(file)
    } else {
        print("file not available")
    }

}

关于ios - 对于 in 循环结果有时在 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917368/

相关文章:

swift - 快速观察多个 NSKeyObservingKeyValueoptions

crash - EXC_BAD_ACCESS-NSString超出范围

objective-c - CGContextStrokePath 在 iOS > 5 中触发 EXC_BAD_ACCESS

iphone - EXC_BAD_ACCESS 在不同 View 中添加和删除 View 时

ios - UIlabel 中的 UITapGestureRecognizer 错误

ios - 按钮到相同的 View ios

ios - 如何使用原始索引路径从数组中删除对象?

ios swift 3 xcode8 beta 圆形 imageView

ios - 在 iOS 应用程序中使用 GitHub 的 OAuth 身份验证 - 它是如何工作的

ios - UISearchController 搜索栏宽度不变