简体   繁体   English

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

[英]What memory management is appropriate for a UITableViewRowAction closure?

Is my use of unowned for self and neither weak nor unowned for tableView appropriate in the following context? 在以下情况下,我对自己使用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]
}

I don't think you need any capture list in this situation. 在这种情况下,我认为您不需要任何capture list

The time when use capture list is when we would create a strong reference cycle, which means those objects are pointing to each other and ARC would consider them still in use since the count isn't 0 . 使用捕获列表的时间是我们创建一个强大的参考周期时,这意味着这些对象相互指向,并且由于计数不为0 ,因此ARC将认为它们仍在使用中。

In editActionsForRowAt situation, the closure is not pointing to anything else, just a block of code to be executed. editActionsForRowAt情况下,闭包不指向其他任何内容,而只是要执行的代码块。

Tapping one of the action buttons executes the handler block stored with the action object. 轻触操作按钮之一将执行与操作对象一起存储的处理程序块。

Read more about editActionsForRowAt here 在此处阅读有关editActionsForRowAt更多信息

In conclusion, it's safe to remove [unowned self] and because you're not using action , you could replace it by _ to make it bit cleaner. 总之,删除[unowned self]是安全的,并且因为您没有使用action ,所以可以将其替换为_以使其更加整洁。 And you don't have to call tableView.reloadData() here as well. 而且您也不必在这里调用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)
}

By the way, Swift document has some great examples of how ARC works and when to use capture list. 顺便说一句,Swift文档提供了有关ARC如何工作以及何时使用捕获列表的出色示例。 You may check it out as well. 您也可以签出。 Link 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM