fatal error: unexpectedly found nil while unwrapping an Optional value in Swift when tried to parse JSON

£可爱£侵袭症+ 提交于 2019-12-02 08:59:45

问题


I've tried to build up a document-based Cocoa app and when I tried to parse JSON in readFromData: ofType: error: method, I got an error: fatal error: unexpectedly found nil while unwrapping an Optional value. The actual line that caused the error is the following:

override func readFromData(data: NSData?, ofType typeName: String?, error outError: NSErrorPointer) -> Bool {
    var error: NSErrorPointer!
    var loadedDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: error) as? NSDictionary // this causes an error
    return true
}

It looks like the NSJSONSerialization.JSONObjectWithData() method caused the error, but why did it issue it?

I changed options: argument to either nil or 0, and also changed error: argument to nil, but nothing solved the issue.

I also ensured that data is not nil.

So what am I missing? I think the JSON method tried to force unwrapping within it, but how can I know that? And how can I escape the fatal error and have my app run properly?

I use Xcode6-beta 3 on Yosemite beta3.


回答1:


Most likely the problem is that you have data that isn't actually JSON, so the deserialisation will return nil, or the data is an array, and converting it to a dictionary will obviously crash.

You don't seem to understand some of the basics. What do you think AllowFragments is going to achieve? And why did you change error to nil? Do you understand what the error variable is there for? It's there to tell you what errors the JSON parser found. By setting the variable to nil, you prevent it from helping you.




回答2:


If the data does not contain a valid JSON object, the JSONObjectWithData function will return a nil, so you need to do a conditional unwrapping as follows:

if let dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: jsonError) as? NSDictionary {
    println("Dictionary: \(dict)")
} else {
   println("nil")
   let resultString = NSString(data: data, encoding: NSUTF8StringEncoding)
   println("Flawed JSON String: \(resultString)")
}

I hope it helps..... e




回答3:


  • In this case outError is supplied as an argument so you should use it (I overlooked that).
  • Looks like this function's purpose is to check whether data is valid JSON.

Then your funciton should be:

override func readFromData(data: NSData?, ofType typeName: String?, error outError: NSErrorPointer) -> Bool {
    if let loadedDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: outError) as? NSDictionary {
       return true
    } else {
       return false
    }
}

Now this function:

  • write error to where the caller specified in ourError should error occur
  • return wheter the data is valid JSON as NSDictionary

FYI I happened to write a JSON handler, too.

  • https://github.com/dankogai/swift-json/

Which includes NSJSONSerialization.JSONObjectWithData.



来源:https://stackoverflow.com/questions/24804322/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-value-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!