【发布时间】:2015-03-16 18:59:35
【问题描述】:
我正在尝试学习 Swift 移植管理 HttpRequest 的 Obj-C 代码,但是当我收到 JSON 格式的响应时,我在尝试访问 NSDictionary 时遇到了问题。
JSON 示例:
{
response = {
id = 1234;
name = a2b3n4h5lkl3;
};
}
我从 HttpRequest completionHandler 收到
(dictionary:NSDictionary?, error:NSError?) -> Void
我想从 NSDictionary 中获取一些值吗?并将它们保存到 var:
let responseDictionary = dictionary!.valueForKey("response") as? NSDictionary
println(responseDictionary!) // The informations are present correctly
if (responseDictionary!.count > 0) {
var testStringAccessId:NSString? = responseDictionary!.valueForKey("id")! as? NSString
println(testStringAccessId) // print nil
println(responseDictionary!.valueForKey("id")!) // print the correct value
if let stringAccessId = responseDictionary!.valueForKey("id")! as? NSString {
self.accessID = stringAccessId
} else {
println("Error No Access ID") // Enter here
completion(success: false)
return // The function exit with error
}
}
我尝试了很多组合,但也许我在可选使用中遗漏了一些东西。奇怪的是,如果我在错误情况下评论返回并尝试从 NSDictionary 获取另一个值,那么这个值是正确的,例如:
if let stringAccessNAME = responseDictionary!.valueForKey("name")! as? NSString {
self.accessNAME = stringAccessNAME // I get the correct value saved in the variable
} else {
println("Error No Access NAME")
completion(success: false)
return
}
有什么帮助吗?
谢谢 麦芽酒
已解决:
使用 NSNumber 代替 NSString。感谢 Jesper
【问题讨论】:
-
听起来您没有正确定位 JSON 中的
id值。一些示例 JSON 将有助于显示问题。 -
使用 JSON 示例编辑
-
id的值似乎不是字符串而是数字。尝试NSNumber而不是NSString- 而不是像我一样猜测(因为我必须这样做,所以我无权访问正在运行的代码),检查调试器中的值和类型。 -
感谢 Jesper,你说的完全正确,我改成 NSNumber 并且工作正常。
标签: ios swift nsdictionary optional