首页 > 解决方案 > 什么内存管理适合 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]
}

标签: swiftmemory-managementclosures

解决方案


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 的工作原理以及何时使用捕获列表。你也可以检查一下。关联


推荐阅读