哪种内存管理适合于UITableViewRowAction闭包?

时间:2019-02-16 17:53:03

标签: swift memory-management closures

在以下情况下,我对自身使用unown还是对tableView既不弱也不对unown合适吗?

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]
}

1 个答案:

答案 0 :(得分:2)

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

使用捕获列表的时间是我们创建一个强大的参考周期的时间,这意味着这些对象相互指向,并且由于计数不是0,因此ARC将认为它们仍在使用中。

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