NSMutableDictionary 路径 "unexpectedly found nil while unwrapping an Optional value"

NSMutableDictionary path "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'

fatal error: unexpectedly found nil while unwrapping an Optional value

变量fileName声明为var fileName: String!

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

正在将文件名声明为字符串!意味着它可能不包含字符串,但您非常确定它包含字符串,并且您接受如果您使用变量 fileName 并且它不包含字符串,您的应用程序会崩溃。这似乎是这里的情况。

除了 gnasher729 的建议之外,另一个潜在的问题是 NSDictionaries 及其子类的 contentsOfFile 初始值设定项:

Return Value:

An initialized dictionary—which might be different than the original receiver—that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary.

因此,如果该字典存在问题,当您在此行中强制解包时

var dictionary = NSMutableDictionary(contentsOfFile: imagesPath)!

它会崩溃。

正如其他人所指出的,问题很可能是您正在使用的强制解包选项之一。 ! 有时被称为 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.
        }
    }