表格视图单元格按钮关闭是否需要弱自我 [英] Is weak self needed for table view cell button closure

查看:50
本文介绍了表格视图单元格按钮关闭是否需要弱自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试避免保留周期时,是否有必要在UITableViewCell按钮操作中使用 [weak self] in ?示例:

在ViewController的 cellForRow

  cell.buttonAction = {(单元格)[弱自我]在self.someFunction()} 

在TableViewCell类中

  var buttonAction:((UITableViewCell)->无效)?@IBAction func buttonPressed(_发件人:任意){buttonAction?(个体经营)} 

解决方案

要考虑的关键是:

  var buttonAction:((UITableViewCell)->无效)? 

您打算在实例属性中长期存储功能.

现在考虑谁指/拥有谁.视图控制器拥有其视图,该视图或拥有拥有单元格的表视图.同时,细胞拥有功能.如果函数强烈引用我刚才提到的任何对象,则那是一个保留周期.这是一个经典保留周期,这是保留周期如何形成的绝对模型.


[[我想补充一下我如何测试这些东西.有一种非常便宜和简便的方法:将视图控制器包装在导航控制器中,再加上一个空白的根视图控制器,以便可以将视图控制器推入.在视图控制器中实现 deinit .现在运行该应用程序,推动您的视图控制器,进行一些操作,然后使用后退"按钮将其弹出.如果未调用 deinit ,则您有一个保留周期.]

In trying to avoid retain cycles, would using [weak self] in in a UITableViewCell button action be necessary? Example:

in ViewController's cellForRow

cell.buttonAction = { (cell) [weak self] in
     self.someFunction()
}

in TableViewCell class

var buttonAction: ((UITableViewCell) -> Void)?

@IBAction func buttonPressed(_ sender: Any) {
     buttonAction?(self)
}

解决方案

The key line to think about is:

var buttonAction: ((UITableViewCell) -> Void)?

You are offering to store a function long-term in an instance property.

Now think about who refers to / owns whom. The view controller owns its view which is-or-owns the table view which owns the cell. Meanwhile the cell owns the function. If the function refers strongly to any of the objects I just mentioned, that is a retain cycle. It is a classic retain cycle, the absolute model of how retain cycles get made.


[I would like to add a word about how I test for these things. There's a really cheap and easy way: wrap your view controller up in a navigation controller plus a blank root view controller, so that you can push your view controller onto it. Implement deinit in your view controller. Now run the app, push your view controller, play with it for a bit, and pop it with the Back button. If deinit isn't called, you've got a retain cycle.]

这篇关于表格视图单元格按钮关闭是否需要弱自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆