我通常更喜欢使用回调,在这个例子中我想知道我是否做对了一切
我有一个带有自定义单元格的 tableView,它有 2 个按钮。
所以我有 2 个回调( block ),当用户点击按钮时我触发它们
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
}
所以我的问题是,默认情况下,回调保留值的强引用,我应该使用吗
[weak self]
避免强引用循环?
同样适用于
indexPath,cell
如果细胞是可重复使用的,那么在这里捕获它们是否正确?
最佳答案
是的,如果要在闭包中使用
self
,请将[weak self]
或[unowned self]
添加到避免保留循环。cell.firstButtonAction = { [weak self] in
不会,捕获的本地值(例如
indexPath
或cell
)不会导致保留周期。
关于swift - 在单元格中正确使用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49243115/