致命错误:索引超出范围,由于一次又一次地按下喜欢和心形按钮



当我一次又一次地按下喜欢和心形按钮时,它会使应用程序崩溃并说"致命错误:索引超出范围"。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) - > Int {
return activityArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) - > UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "activityCell") as!StreamActivityTableViewCell
cell.likeButton.tag = indexPath.row
print("....(cell.likeButton.tag)")
cell.heartButton.tag = indexPath.row
cell.likeButton.addTarget(self, action: #selector(liked(sender: )),
for: .touchUpInside)
cell.heartButton.addTarget(self, action: #selector(loved(sender: )),
for: .touchUpInside)
return cell
}


@objc func liked(sender: UIButton) {
let likebutton = sender.tag
print("---- (likebutton)  ... (sender.tag)")
let headers = ["Authorization": "Bearer (UserDefaults.standard.string(forKey: "
token ")!)"
]
let parameters: Parameters = [
"activity_id": activityArray[sender.tag].id!
]
print(parameters)
Alamofire.request(Constants.likedURL, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers).validate().responseString {
response in
switch (response.result) {
case.success(_):
if (response.result.isSuccess) {
self.activityArray.removeAll()
self.activityShown()
}
case.failure(_):
print("Error message:(response.error!.localizedDescription)")
let alert = UIAlertController(title: "Sorry", message: "(response.error!.localizedDescription)", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
break
}
}
}


func activityShown(){
SVProgressHUD.show()
let headers = ["Authorization":"Bearer (UserDefaults.standard.string(forKey: "token")!)"]
Alamofire.request(Constants.activitiesURL,method: .get,   encoding: JSONEncoding.default, headers: headers).responseJSON { response in
if response.result.isSuccess {
let ActivityJSON : JSON = JSON(response.result.value!)
let activityData = ActivityJSON["data"].arrayValue
let commentData = ActivityJSON["data"].arrayValue
for value in activityData {
let activity = Activity()
activity.name = value["name"].stringValue
activity.content = value["content"].stringValue
activity.published = value["published"].stringValue
activity.thumbnail = value["users"]["photo_thumb"].stringValue
activity.likesCount = value["likes_count"].intValue
activity.liked = value["liked"].intValue
activity.heartCount = value["heart_count"].intValue
activity.hearted = value["hearted"].intValue
activity.commentsCount = value["comments_count"].intValue
activity.commented = value["commented"].intValue
activity.id = value["id"].intValue
activity.currentID = value["users"]["user_id"].intValue
self.activityArray.append(activity)
SVProgressHUD.dismiss()
}
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
else {
print("Error (String(describing: response.result.error))")
}
}
}

在这里,我正在使用观察者,从sender.tag获取index.row,当我点击喜欢或心形按钮时,该API点击并给出响应。当我点击的次数比应用程序崩溃的次数更多时。

你为什么要在成功时这样做?

self.activityArray.removeAll()

下次调用此函数时,将索引到数组中

"activity_id": activityArray[sender.tag].id!

但根据您显示的代码,它将是空的

如果activityArray正在更改并且它似乎用于表行,则需要调用tableView.reloadData()来清空表

编辑 -- 在看到更新的代码后。

你做错了几件事

  1. 在知道是否有新数据之前删除数据
  2. 您正在后台线程中重新加载数据 - 它始终需要在主线程中

所以

  1. 删除liked(sender:)中的行self.activityArray.removeAll()
  2. 在此处添加该行
if response.result.isSuccess {
let ActivityJSON : JSON = JSON(response.result.value!)

//// HERE is where we know we are replacing the data
self.activityArray.removeAll()

let activityData = ActivityJSON["data"].arrayValue
let commentData = ActivityJSON["data"].arrayValue

最后

self.tableView.reloadData()
self.refreshControl.endRefreshing()

这段代码需要像这样

DispatchQueue.main.async {
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}

因为网络调用可能不会在主线程上完成,但所有 UI 代码都需要在主线程上完成。

编辑:正如克劳斯在他们的评论中提到的,更好的方法可能是使用deleteRows/insertRows并执行BatchUpdates

我建议你首先使用 reloadData() 获取所有内容 - 然后去阅读 https://developer.apple.com/documentation/uikit/uitableview/1614960-deleterows 和 https://developer.apple.com/documentation/uikit/uitableview/1614879-insertrows 和 https://developer.apple.com/documentation/uikit/uitableview/2887515-performbatchupdates 的苹果文档,也许可以观看本教程:https://www.youtube.com/watch?v=MC4mDQ7UqEE

如果你这样做 - 特别是当你不重新加载整个表格时 - iOS将做更少的工作,并制作更好的默认动画。

最新更新