单元格中回调的正确使用 [英] Correct usage of callbacks in cell

查看:22
本文介绍了单元格中回调的正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常更喜欢使用回调,在这个例子中想知道我是否一切都正确

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?

推荐答案

  1. 是的,如果要在闭包中使用 self,请将 [weak self][unowned self] 添加到避免保留循环.

  1. 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

  • 不,像 indexPathcell 这样捕获的本地值不会导致保留循环.

  • No, captured local values like indexPath or cell don't cause retain cycles.

    这篇关于单元格中回调的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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