gpt4 book ai didi

swift - 弱或无主或无

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:38 25 4
gpt4 key购买 nike

我有一个 ViewController 类,如下所示:

class ViewController {

var viewModel = ViewModel()

viewDidLoad() {
self.viewModel.showAlert = { [weak self] in
self?.alert()
}
}

func alert() {
// alert logic
}
}

这是 ViewModel 类

class ViewModel {
var showAlert: (() -> Void)?
}

现在,这是否会创建一个强大的引用循环?

如果这创建了一个,那么使用什么 - weak 还是 unowned?

最佳答案

不会创建一个强引用循环,因为您使用了weak self

ViewController 持有对 ViewModel 的强引用。 ViewModel 持有对闭包的强引用。闭包包含对 ViewController引用:

VC ---strong---> ViewModel
^ |
| strong
| v
--------weak-----closure

只要 ViewController 被释放(例如,当您关闭它时就会发生这种情况),ViewModel 也会被释放。

关于swift - 弱或无主或无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49586264/

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