我正在尝试从Swift中的NSSearchPathForDirectoriesInDomains
获取文件路径。它返回NSString
,但如果我尝试对其进行任何操作(甚至打印),我会收到Thread 1: EXC_BAD_ACCESS (code=1 address=0x20)
错误。
我已经把头撞到了墙上一段时间了,因为这种情况发生在几个地方,我尝试了很多代码。
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
NSURLConnection(request: request, delegate: self)
if (request.URL?.absoluteString!.rangeOfString("attachment=true") != nil) {
// This line only succeeds with 'as! [NSString]'. If I try 'as! [String]' it fails.
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as! [NSString]
// On this line I get the error if I leave the above array as [AnyObject]
// And try and convert this with 'as! String'. Succeeds with 'as! NSString'.
let pathString = paths[0]
// This line always fails with the error. I can't interact with pathString without it failing.
// Including something as simple as asking for its length.
let filePath = pathString.stringByAppendingPathComponent("download.pdf")
}
}
奇怪的是,调试器似乎将paths
数组显示为空(但不是nil),但如果超过该行,则pathString
被正确设置。
这在iOS 7.1,模拟器和设备中发生。我没有机会在iOS 8中测试它.Xcode 6.3,Swift 1.2