什么内存管理适合UITableViewRowAction闭包?

问题描述 投票:1回答:1

在下面的上下文中,对于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]
}
swift memory-management closures
1个回答
2
投票

在这种情况下,我认为你不需要任何capture list

使用捕获列表的时间是我们创建一个强引用循环的时间,这意味着这些对象彼此指向,ARC会认为它们仍然在使用,因为计数不是0

editActionsForRowAt情况下,闭包不指向任何其他东西,只是要执行的代码块。

点击其中一个操作按钮可执行与操作对象一起存储的处理程序块。

了解更多关于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

© www.soinside.com 2019 - 2024. All rights reserved.