mnewmedia mnewmedia - 1 day ago 4
Swift Question

for in loop results sometimes in EXC_BAD_ACCESS

Sometimes i get a

EXC_BAD_ACCESS
error in this code:

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


But it occurs only sometimes, any idea how to figure out what is causing this?

Answer

You are getting the crash because item[file] is nil and you are using force unwrapping, go with optional binding like this

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

}
Comments