2015-08-19 44 views
1

我有一個簡單:的NSMutableDictionary路徑「意外發現零而展開的可選值」

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

而且它獲得最後一個行之後崩潰,並給我的醇」

fatal error: unexpectedly found nil while unwrapping an Optional value

變量fileName被聲明爲var fileName: String!

我無法寫入路徑。我究竟做錯了什麼?

回答

2

除了gnasher729的建議,另一個潛在的問題是,contentsOfFile初始化爲NSDictionaries及其子類:

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

它會崩潰。

+0

是的,我需要先將文件保存到位置。所以我說如果NSMutableDictionary(contentsOfFile:imagesPath)!是零,保存所需的文件。謝謝大家。 – MScottWaller

1

將fileName聲明爲String!意味着它可能不包含字符串,但是您確定它確實如此,並且您接受如果使用變量fileName並且它不包含字符串,則應用程序崩潰。這似乎就是這種情況。

+1

沒有OP說,它得到的最後一行有關係嗎?這不是意味着'NSMutableDictionary(contentsOfFile:imagesPath)'返回'nil'嗎? – Cole

0

正如其他人所指出的,這個問題很可能是您正在使用的解包合同的選項之一。 !有時被稱爲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. 
     } 
    } 
相關問題