ios - 使用 NSFileManager 检索多个值时收到 "fatal error: unexpectedly found nil while unwrapping an Optional value"

标签 ios xcode swift nsfilemanager

当我尝试使用 NSFileManager 检索多个值时收到以下错误:fatal error: unwrapping an Optional value unwrappedly found nil

这是我的代码:

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)

我已经测试了这个函数调用的多个变体,但没有什么不同

谢谢

最佳答案

你为什么不打开它们?尝试这样的事情

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

关于ios - 使用 NSFileManager 检索多个值时收到 "fatal error: unexpectedly found nil while unwrapping an Optional value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29829218/

相关文章:

ios - 如何向 VPN 添加代理配置?

objective-c - IOS:使用 iPad KeyBoard 的回车键操作

ios - 如何检查文件是否存在使用 swift,从 objective c 重写

iphone - 找出iOS用户来自哪里,为新浪微博整合?

iphone - 从 NSDictionary 填充表格 View

objective-c - quartz 芯。同一路径上的纯色矩形和渐变色圆圈

ios - MFMessageComposeViewController canSendText 类在模拟器上返回 YES

ios - Pages 和 Keynote URL Scheme

ios - Swift 2 - 如何从 Alamofire.responseJSON 获取数据

ios - 如何添加 iOS 10 默认注释/图钉?