[英]Why am I getting an NSInternalInconsistencyException after my second UITableView search?
[英]Why am I getting a blank UITableView after parse JSON in Swift 4?
我不知道為什么單元格不返回數據。
我可以使用Decodable正常解析,這意味着它可以正常工作。
我一直在嘗試所有發現的方法,但都沒有成功。
struct MuscleGroup: Decodable {
let ExcerciseID: String
let description: String
let excerciseName: String
let muscleGroup: String
}
class ExerciseListViewController: UITableViewController {
var muscleGroup = [MuscleGroup]()
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return muscleGroup.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExerciseList", for: indexPath) as! ExcerciseList
let muscle = muscleGroup[indexPath.row]
cell.textLabel!.text = muscle.excerciseName
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.muscleGroup[indexPath.row])
tableView.deselectRow(at: indexPath, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
getJson()
}
func getJson(){
guard let url = URL(string: "https://jsonurl") else { return }
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let muscles = try JSONDecoder().decode([MuscleGroup].self, from: data)
for muscle in muscles {
let muscleGroup = muscle.excerciseName
print(muscleGroup)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
}.resume()
}
如果將var muscleGroup = String更改為[“ Chest”,“ Back”,“ Abdominals”,“ Arms”,“ Legs”],它將正確返回。
另外,控制台上的打印結果將返回需要在“表視圖”中的所有數據。
我究竟做錯了什么?
在您的getJson函數中,此行
let muscleGroup = muscle.excerciseName
正在創建一個新的局部變量,名為muscleGroup
,將行更改為
self.muscleGroup.append(muscle.excerciseName)
即擺脫let
append
值append
到主數組變量
同時移動
DispatchQueue.main.async {
self.tableView.reloadData()
}
到外面的用於循環muscles
,你正迫使表重新加載每個條目,而不是當你完成
因為您可能想使用整個結構
更換
var muscleGroup = [String]()
同
var muscleGroups = [MuscleGroup]()
更換
let muscles = try JSONDecoder().decode([MuscleGroup].self, from: data) for muscle in muscles { let muscleGroup = muscle.excerciseName print(muscleGroup) DispatchQueue.main.async { self.tableView.reloadData() } }
同
self.muscleGroups = try JSONDecoder().decode([MuscleGroup].self, from: data) DispatchQueue.main.async { self.tableView.reloadData() }
更換
cell.textLabel?.text = self.muscleGroup[indexPath.row]
同
cell.textLabel?.text = self.muscleGroups[indexPath.row].muscleGroup
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.