gpt4 book ai didi

ios - 以正确的方式分配回调

转载 作者:行者123 更新时间:2023-11-28 05:54:37 25 4
gpt4 key购买 nike

我对在我的一个类中从另一个类获取 callback 的 2 种方法感到困惑。

这是我的场景:

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

我想在我的 Controller 类中使用这个回调。我知道这两种方式:

方法一:

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
}

在第一种方法中,引用很弱,方法 2 是否相同?哪个是更好的方法?也请添加适当的解释。

最佳答案

在直接选择上述选项之一之前,我们应该先了解什么是[weak self]部分。 [weak self] 调用了闭包捕获列表;这是什么原因?!好吧,请记住,Swift 中的闭包是引用类型,每当您将函数或闭包分配给常量或变量时,您实际上是将该常量或变量设置为对该函数的引用或关闭。这意味着在某些时候,如果您在代码中滥用闭包,可能会导致保留循环

引自 The Swift Programming Language - Closures :

If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its members, you will create a strong reference cycle between the closure and the instance. Swift uses capture lists to break these strong reference cycles.

这意味着如果您打算在闭包主体中使用 self,则必须遵循第一种方法。在捕获列表中使用 weak item self 解决(防止)保留循环,这就是为什么你会选择第一种方法。

有关如何完成的更多信息,我强烈建议查看:自动引用计数,Resolving Strong Reference Cycles for Closures部分。

关于ios - 以正确的方式分配回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51836494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com