展开可选值时发现 nil JSON 序列化
Found nil while unwrapping optional value JSON Serialization
我执行 NSURLSession
从 php 获取数据,这是 JSON。当我执行 NSJSONSerialization
并将其存储为 NSArray
时,一切正常,但是当我尝试访问其中的一个元素以将其放入 table 视图时,它崩溃并出现错误 found nil while展开可选值。 JSON 它 returns 看起来像这样:
[
{
"title":"data",
"value":"data"
}, ...
]
我用来获取值的代码是:
self.arrayJSON[indexPath.row]["title"]
当我在 Xcode 控制台中尝试这个时 returns 这个:
▿ Optional(some data)
- Some : some data
编辑:
JSON解析代码:
let task = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
do {
let responseJSON : NSArray = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSArray
self.arrayJSON = NSMutableArray(array: responseJSON)
dispatch_async(dispatch_get_main_queue()) {
self.listaAnuncios.reloadData()
}
} catch {
print("json error")
}
}
task.resume()
我找到问题了!这不是因为访问元素,而是因为单元格为零。我正在使用这个:
let cell : CustomCell = CustomCell()
我为此更改了它:
let cell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomCell
我执行 NSURLSession
从 php 获取数据,这是 JSON。当我执行 NSJSONSerialization
并将其存储为 NSArray
时,一切正常,但是当我尝试访问其中的一个元素以将其放入 table 视图时,它崩溃并出现错误 found nil while展开可选值。 JSON 它 returns 看起来像这样:
[
{
"title":"data",
"value":"data"
}, ...
]
我用来获取值的代码是:
self.arrayJSON[indexPath.row]["title"]
当我在 Xcode 控制台中尝试这个时 returns 这个:
▿ Optional(some data)
- Some : some data
编辑:
JSON解析代码:
let task = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
do {
let responseJSON : NSArray = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSArray
self.arrayJSON = NSMutableArray(array: responseJSON)
dispatch_async(dispatch_get_main_queue()) {
self.listaAnuncios.reloadData()
}
} catch {
print("json error")
}
}
task.resume()
我找到问题了!这不是因为访问元素,而是因为单元格为零。我正在使用这个:
let cell : CustomCell = CustomCell()
我为此更改了它:
let cell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomCell