单元格中回调的正确使用 [英] Correct usage of callbacks in cell
问题描述
我通常更喜欢使用回调,在这个例子中想知道我是否一切都正确
I usually prefere to use callbacks, and in this example wanted to know if I get everything correct
我有一个带有自定义单元格的 tableView,它有 2 个按钮.
I have a tableView with custom cell, which has 2 buttons.
所以我有 2 个回调(块),当用户点击按钮时我会触发它们
So I have 2 callbacks (blocks), and when user tap the buttons I fire them
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.firstButtonAction = {
print(indexPath,cell)
print(self)
}
cell.secondButtonAction {
print(indexPath,cell)
print(self)
}
return cell
}
所以我的问题是,默认情况下,回调保持值的强引用,我应该使用
So my question is because, by default, callbacks keep value's strong reference, should I use
[弱自我]
避免强引用循环?
和
索引路径,单元格
如果细胞可以重复使用,在这里捕捉它们是否正确?
if cells are reusable, is it correct to catch them here?
推荐答案
是的,如果要在闭包中使用
self
,请将[weak self]
或[unowned self]
添加到避免保留循环.
Yes, if
self
is going to be used in the closure add[weak self]
or[unowned self]
to avoid retain cycles.
cell.firstButtonAction = { [weak self] in
不,像 indexPath
或 cell
这样捕获的本地值不会导致保留循环.
No, captured local values like indexPath
or cell
don't cause retain cycles.
这篇关于单元格中回调的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!