swift - 什么样的内存管理适合 UITableViewRowAction 闭包?

标签 swift memory-management closures

我对 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/

相关文章:

ios - No Such Module Found 在 Podspec 中添加依赖

c - C free() 是如何工作的?

JavaScript:函数及其作用域/词法环境如何传递?

javascript - 无法访问 Javascript 函数包装器内的函数?

swift - 在 Swift 中使用 MPMoviePlayerController() 播放 MP4

ios - 每个顶点颜色的 SceneKit

ios - 将ViewController的uiview换成xib

Java内存清理

linux - 内存使用分析

c# - 像在 Ruby 中一样在 C# 中使用 yield