ios - 致命错误:索引超出范围,由于一次又一次按下like和heart按钮
问题描述
当我一次又一次地按下喜欢和心形按钮时,它会使应用程序崩溃并说“致命错误:索引超出范围”。
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()
以清空表格
编辑——在看到更新的代码之后。
你有几件事不对
- 在知道是否有新数据之前删除数据
- 您正在后台线程中重新加载数据——它总是需要在主线程中
所以,
self.activityArray.removeAll()
删除行liked(sender:)
- 在此处添加该行
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 和 performBatchUpdates
我建议您首先使用 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 将做更少的工作并制作更好的默认动画。
推荐阅读
- python - 如何通过 Pandas 索引选择或跳过唯一行
- java - 将相同项目添加到其他实体时,Spring JPA 实体正在丢失数据
- javascript - Nuxt i18n 在语言切换时重置数据对象
- java - 从按钮单击上的线程值设置 JTextField 不起作用
- python - 更新散景时出现问题:[WinError 126] 找不到指定的模块
- javascript - 无法读取未定义的属性 getExif
- mysql - 计算每个每日活跃用户的平均会话时长?
- c# - 从 Button Form App Visual Studio 调用函数
- github - Github Actions 中的 PR 更新事件
- twilio - Twilio 给一条短信或彩信一个被叫的 id