gpt4 book ai didi

ios - 存储为变量的 Swift 闭包会产生内存泄漏

转载 作者:搜寻专家 更新时间:2023-11-01 06:27:46 24 4
gpt4 key购买 nike

我在将闭包定义为变量时有一个保留周期。

变量定义如下:

public class MyCell: UICollectionViewCell {
public var callback: ((MyCell)->Void)?
}

如果我使用委托(delegate)而不是闭包,保留周期就会消失,但我想知道如何为 future 的情况使用闭包来定义它。

我尝试将回调变量设置为weak,但是,正如我所想,weak 属性只能应用于类和类绑定(bind)协议(protocol)类型。

编辑

用法:

class CustomController: UIViewController {
private func onActionOccurs(_ cell: MyCell) {
cell.backgroundColor = .red // For example
}

// After dequeuing the cell:
{
cell.callback = onActionOccurs(_:)
}
}

谢谢

最佳答案

如果你不需要使用 self,那么你可以使用单元格本身,并像这样修改单元格中的闭包实现

public class MyCell: UICollectionViewCell {
public var callback: (()->Void)?
}

然后就可以使用了,就像这个例子

class CustomController: UIViewController {
private func onActionOccurs(_ cell: MyCell) {
cell.backgroundColor = .red // For example
}

// After dequeuing the cell:
{
cell.callback = {
cell.backgroundColor = .red // For example
}
}
}

但是如果您需要使用 ViewController 方法,那么您需要使用 [weak self] 捕获列表如果您需要使用 UIViewController 方法

class CustomController: UIViewController {
private func onActionOccurs(_ cell: MyCell) {
cell.backgroundColor = .red // For example
}

// After dequeuing the cell:
{
cell.callback = { [weak self] in
guard let self = self else { return }

self.viewControllerMethod()
}
}
}

关于ios - 存储为变量的 Swift 闭包会产生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51629369/

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