NSMutable字典路径"unexpectedly found nil while unwrapping an Optional value"



我有一个简单的:

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String 
let dataPath = documentsPath.stringByAppendingPathComponent("Images")
let imagesPath = dataPath.stringByAppendingPathComponent(fileName)
var dictionary = NSMutableDictionary(contentsOfFile: imagesPath)!

当它写到最后一行时它崩溃了,给了我一个ol'

致命错误:在展开可选值

时意外发现nil

变量fileName声明为var fileName: String!

我也无法写入路径。我做错了什么?

除了gnasher729的建议之外,另一个潜在的问题是nsdictionary及其子类的contentsOfFile初始化器:

返回值:

一个初始化的字典(可能与原始接收者不同),它包含在path处的字典,如果存在文件错误或文件内容是无效的字典表示,则为nil。

如果那个字典有问题,当你在这行强制展开它时

var dictionary = NSMutableDictionary(contentsOfFile: imagesPath)!

会崩溃

将文件名声明为字符串!意味着它可能不包含字符串,但你很确定它包含,如果你使用变量fileName而它不包含字符串,你接受你的应用程序崩溃。这里的情况似乎就是这样。

正如其他人注意到的那样,问题可能是您正在使用的强制展开可选项之一。!有时被称为Bang!是有原因的。他们有爆炸的倾向:)一次打开一个东西并使用一些print语句将帮助您找出问题所在:

if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String,
    let filePath = filePath {
        println("Determined that both documentsPath and filePath are not nil.")
        let dataPath = documentsPath.stringByAppendingPathComponent("Images")
        let imagesPath = dataPath.stringByAppendingPathComponent(fileName)
        if let dictionary = NSMutableDictionary(contentsOfFile: imagesPath) {
            println("Determined that dictionary initialized correctly.")
            // do what you want with dictionary in here. If it is nil
            // you will never make it this far.
        }
    }

相关内容

最新更新