ios - Swift 5:从 tableView numberOfRowsInSection 返回数组计数时索引超出范围
问题描述
我几乎解决了这个问题。这是唯一需要解决的问题。
这就是我要解析的内容: https ://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=API_KEY
sample[0].articles.count 出现索引超出范围的错误
我正在尝试用我解析的数据填充标签。我试过了,它只返回 1 个单元格。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sample.count
}
ViewController.swift
import UIKit
struct News: Decodable {
let articles: [Article]
struct Article: Decodable {
let title: String?
let urlToImage: String?
let description: String?
}
}
class ViewController: UIViewController {
@IBOutlet weak var table: UITableView!
var sample = [News]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
getJson()
table.delegate = self
table.dataSource = self
}
func getJson() {
let urlString = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=e07d26ea273d41e2af174b026aea27b5"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
self.sample = [try JSONDecoder().decode(News.self, from: data)]
print(self.sample[0].articles.count)
for dict in self.sample {
for sam in dict.articles {
print(sam.title!)
}
}
DispatchQueue.main.async {
//reload tableView data
self.table.reloadData()
}
} catch let jsonErr {
print("json error: ", jsonErr)
}
}.resume()
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sample[0].articles.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(100)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
let json = sample[0].articles[indexPath.row]
cell.name.text = "\(json.title!)"
cell.link.text = "\(json.description!)"
cell.imageUrl.text = "\(json.urlToImage!)"
return cell
}
}
解决方案
您正在sample
异步设置,在包含任何内容tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
之前调用。sample
以下更改将防止崩溃。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sample.first?.articles.count ?? 0
}
推荐阅读
- python - 打印度数符号 (°) 会产生“未知符号”(romb 中的问号)
- c++ - C++ 编译器如何检测非常量函数体?
- ruby-on-rails - 没有路由映射到我的控制器的操作
- r - 使用 R 访问 Facebook 的 API,无需创建应用程序
- c# - 带有 LINQ 查询的长处理方法应该在队列中
- c - 编译步骤
- angular - 即使请求从 Angular 客户端传递访问令牌,Azure AD WebAPI 也会返回 Not Authorization
- windows - 如何在 Windows 7 中使用波浪号复制文件名?
- ksqldb - 使用 KSQL 加入 KTable-KTable 时,单独设置状态的保留时间
- machine-learning - 将管道中的矢量化特征标记为原始数组名称 (PySpark)