我对 self 使用 unowned 而对 tableView 使用 neither weak nor unowned 在以下上下文中是否合适?
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]
}
最佳答案
我认为在这种情况下您不需要任何捕获列表
。
使用捕获列表的时候我们会创建一个强引用循环,这意味着这些对象相互指向并且 ARC 会认为它们仍在使用中,因为计数不是 0
.
在editActionsForRowAt
情况下,闭包没有指向其他任何东西,只是要执行的代码块。
Tapping one of the action buttons executes the handler block stored with the action object.
阅读有关 editActionsForRowAt
的更多信息 here
总而言之,删除 [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 如何工作以及何时使用捕获列表。您也可以检查一下。 Link
关于swift - 什么样的内存管理适合 UITableViewRowAction 闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54725999/