【问题标题】:Swift - Cast from 'NSData?' to unrelated type 'NSDictionary' always fails斯威夫特 - 来自“NSData?”到不相关的类型“NSDictionary”总是失败
【发布时间】:2015-05-01 02:25:29
【问题描述】:

我使用的是最新版本的 Xcode,但出现以下错误:“Cast from 'NSData?'到不相关的类型 'NSDictionary' 总是失败"

使用此代码:

let dataObject = NSData(contentsOfURL: location)

let weatherDictionary: NSDictionary = NSJSONSerialization.dataWithJSONObject(dataObject!, options: nil, error: nil) as! NSDictionary

编程语言:Swift

更新代码:

if (error == nil) {
                let dataObject = NSData(contentsOfURL: location)

                let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary

                }
  • 现在在我运行我的应用程序时获取断点。

对不起,我还是堆栈溢出的新手

【问题讨论】:

  • 是的,它是 NSDictionary
  • let weatherDictionary : AnyObject! = NSJSONSerialization.JSONObjectWithData(dataObject, options: NSJSONReadingOptions.MutableContainers, error: nil) 使用此代码并检查 weatherDictionaryNSArrayNSDictionary
  • 仍然出现错误
  • 请返回并编辑您的原始问题。在底部添加一个“##Edit”块。发布您的新代码和您收到的确切错误消息,并告诉我们哪一行引发了错误。
  • @Python_is_cool - 两点:首先,如果您遇到问题,请不要将nil 用于error 参数。这是一种让解析器解释失败原因的机制。有错误很疯狂,但不想看到错误是什么。其次,您应该将NSData 转换为字符串并直观地检查它(也许编辑向我们展示它的样子的问题)。例如,println(NSString(data: dataObject, encoding: NSUTF8StringEncoding))。当我们查看实际的响应字符串时,问题可能会变得不言而喻。

标签: ios swift


【解决方案1】:

当然失败了。你调用了错误的方法。

NSJSONSerialization 方法 dataWithJSONObject 接受一个可以转换为 JSON 的对象并返回 NSData。它总是返回 NSData(或 nil)。在任何情况下,它都不会返回字典。

如果您想要将 NSData 转换为集合对象,那么您想使用 JSONObjectWithData 方法。

【讨论】:

  • 让 dataObject = NSData(contentsOfURL: location) 让 weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary 还是不行
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
相关资源
最近更新 更多