我执行 NSURLSession
从 PHP 中获取数据,这是一个 JSON。当我执行 NSJSONSerialization
并将其存储为 NSArray
时,一切正常,但是当我尝试访问其中的一个元素以将其放入 TableView 时,它因发现错误而崩溃展开可选值时为 nil。它返回的 JSON 如下所示:
[
{
"title":"data",
"value":"data"
}, ...
]
我用来获取值的代码是:
self.arrayJSON[indexPath.row]["title"]
当我在 Xcode 控制台中尝试这个时返回这个:
▿ 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
关于php - 在展开可选值 JSON 序列化时发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36010520/