对于in循环结果有时在EXC_BAD_ACCESS中

时间:2016-12-01 17:59:40

标签: 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)!)
    }
}

但它有时只会发生,任何想法如何找出造成这种情况的原因?

1 个答案:

答案 0 :(得分:2)

由于item[file]nil并且您正在使用强制展开,因此请使用可选绑定

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")
    }

}