代码之家  ›  专栏  ›  技术社区  ›  Sharad Chauhan Muhammad Bilal Hussain

以正确的方式分配回调

  •  1
  • Sharad Chauhan Muhammad Bilal Hussain  · 技术社区  · 7 年前

    callback

    class TableCell: UITableViewCell {
      var callBack:(()->())?
    }
    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier", for: indexPath) as! CustomCell
        cell.callBack = {[weak self] () in
        }
        return cell
    }
    

    func callBackFunction() {
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier", for: indexPath) as! CustomCell
        cell.callBack = callBackFunction
        return cell
    }
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ahmad F    7 年前

    [weak self]

    The Swift Programming Language - Closures :

    如果将闭包分配给类实例的属性,并且 闭包通过引用该实例或其 成员,您将在闭包之间创建一个强引用循环 以及实例。斯威夫特使用 捕获列表 打破这些强大 参考周期。

    这意味着如果你打算使用 self 在封闭体中。使用捕获列表中的弱项self可以解决(防止)保留循环,这就是为什么要使用第一个方法的原因。

    关于如何做的更多信息,我强烈建议检查:自动参考计数, Resolving Strong Reference Cycles for Closures 部分。