swift - 什么内存管理适合 UITableViewRowAction 闭包?
问题描述
在以下情况下,我对自己使用 unowned 和对 tableView 既不弱也不无主的使用是否合适?
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "Delete") { [unowned self] (action, indexPath) in
self.habitsManager.remove(at: indexPath.row)
self.adjustForRowCount()
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.reloadData()
}
return [delete]
}
解决方案
capture list
我认为在这种情况下你不需要任何东西。
使用捕获列表的时间是我们创建强引用循环的时候,这意味着这些对象相互指向,ARC 会认为它们仍在使用中,因为计数不是0
。
在editActionsForRowAt
某些情况下,闭包不指向其他任何东西,只是要执行的代码块。
点击其中一个操作按钮会执行与操作对象一起存储的处理程序块。
阅读更多关于editActionsForRowAt
这里
总之,删除它是安全的,[unowned self]
并且因为您不使用action
,您可以将其替换_
为使其更清洁。你也不必在tableView.reloadData()
这里打电话。
let delete = UITableViewRowAction(style: .destructive, title: "Delete") {(_, indexPath) in
self.habitsManager.remove(at: indexPath.row)
self.adjustForRowCount()
tableView.deleteRows(at: [indexPath], with: .fade)
}
顺便说一句,Swift 文档中有一些很好的例子来说明 ARC 的工作原理以及何时使用捕获列表。你也可以检查一下。关联
推荐阅读
- reactjs - 如何获取导航栏上的值总数
- firebase - 在 pubspec.yaml 文件中添加 firebase_auth 或 cloud_firestore 时构建失败并出现异常(firebase_core 正在工作):
- docker - 参数化 docker-compose 图像拉取
- node.js - 如何在 Amazon Linux 2 平台上使用 Elastic Beanstalk 部署的 Nodejs 中实现 gzip 压缩?
- r - ggplot子集一个函数中的列表
- visual-studio - 在源代码管理比较功能中取消绑定滚动
- javascript - 在 Google 地图上显示/隐藏标记
- python - 通过 Github 部署 Heroku,超级用户创建
- javascript - 在 onChange 事件值的 flatpickr 中未分配 alpinejs
- c# - OpenRemoteBaseKey UnauthorizedAccessException:试图执行未经授权的操作