2015-04-23 20 views
0

我收到以下錯誤,當我嘗試使用的NSFileManager檢索多個值時收到<code>fatal error: unexpectedly found nil while unwrapping an Optional value</code></p> <p>這裏是我的代碼:「致命錯誤:意外發現零而展開的可選值」使用的NSFileManager檢索多個值

class func loadGameData() -> (HighScore: Int, HasCompletedTutorial: Bool) { 
    // getting path to GameData.plist 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray 
    let documentsDirectory = paths[0] as! String 
    let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist") 
    let fileManager = NSFileManager.defaultManager() 

    //check if file exists 
    if(!fileManager.fileExistsAtPath(path)) { 
     // If it doesn't, copy it from the default file in the Bundle 
     if let bundlePath = NSBundle.mainBundle().pathForResource("GameData", ofType: "plist") { 
      let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath) 
      fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil) 
     } 
    } 

    let resultDictionary = NSMutableDictionary(contentsOfFile: path) 
    var myDict = NSDictionary(contentsOfFile: path) 

    if let dict = myDict { 
     //loading values - THIS IS WHERE THE ERROR OCCURS 
     let HighScore: AnyObject = dict.objectForKey("HighScore")! 
     let CompletedTutorial: AnyObject = dict.objectForKey("HasCompletedTutorial")! 

     return (Int(HighScore as! NSNumber), Bool(CompletedTutorial as! NSNumber)) 
    } 

    return (0, false) 
} 

我已經測試了他們自己的兩條線,他們完美地工作。但他們似乎沒有一起工作

這裏是用來調用函數

let val = GameData.loadGameData() 
println(val.HighScore) 
println(val.HasCompletedTutorial) 

我已經測試此函數調用的多個變體的代碼,並沒有作出區別

謝謝你

+1

哪條線你得到的錯誤? '路徑'零? – RehcsifMit

+0

@RehcsifMit錯誤發生在這兩行上:'讓HighScore:AnyObject = dict.objectForKey(「HighScore」)! 讓CompletedTutorial:AnyObject = dict.objectForKey(「HasCompletedTutorial」)! ' – Oliver

+1

除非你的字典保證有這些鍵,否則你最好使用'?'解包並明確檢查爲零。 – RehcsifMit

回答

1

你爲什麼不打開它們?嘗試類似這樣的

if let dict = myDict { 
    if let 
     highScore = dict.objectForKey("HighScore"), 
     completedTutorial = dict.objectForKey("HasCompletedTutorial") 
    { 
     return (Int(highScore as! NSNumber), Bool(completedTutorial as! NSNumber)) 
    } 
} 
+0

謝謝,它現在有效 – Oliver

相關問題