[英]MVVM: binding the View with the ViewModel with closures, unowned or weak self?
I'm implementing a simple Master-Detail app where the Master viewController
manages a table view which shows the results of a call to a REST service. 我正在实现一个简单的Master-Detail应用程序,其中Master
viewController
管理一个表视图,该视图显示对REST服务的调用结果。 The Detail viewController
manages a view where I show more information about the item selected in the Master . Detail
viewController
管理一个视图,其中显示有关在Master中选择的项目的更多信息。 Common scenario. 常见情况。
I'm trying to apply MVVM
pattern. 我正在尝试应用
MVVM
模式。 In the Master viewController
, I create and initialize its viewModel
this way: 在Master
viewController
,我viewModel
这种方式创建并初始化它的viewModel
:
lazy private var viewModel: ListViewModel = {
return ListViewModel()
}()
override func viewDidLoad() {
super.viewDidLoad()
initViewModel()
}
private func initViewModel() {
viewModel.onModelChange = { [weak self] () in
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
viewModel.fetchData()
}
My question is: in the closure provided to the viewModel
, should self
be weak
or unowned
instead? 我的问题是:在提供给
viewModel
的闭包中,应该是self
weak
还是unowned
? I found an example implementing an scenario similar to mine that was setting it to weak
, and another one setting it to unowned
, so I'm not completely clear. 我发现了一个实现类似于我的方案的例子,它将它设置为
weak
,另一个将它设置为unowned
,所以我不完全清楚。
[unowned self] . [无主的自我] 。 This tells your model not to hold a strong reference to
ViewController
这告诉您的模型不要持有对
ViewController
的强引用
Apple document states it clearly that: Apple文件明确指出:
“Like weak references, an unowned reference does not keep a strong hold on the instance it refers to.
“就像弱引用一样, 无主引用并不能保持对它引用的实例的强烈保持。 Unlike a weak reference, however, an unowned reference is assumed to always have a value”.
然而,与弱引用不同,假定无主引用始终具有值“。
In your case , there is always be ViewController
. 在您的情况下 ,总是有
ViewController
。 So benefit of unowned reference is it's nonoptional
. 因此,无主参考的好处是它的
nonoptional
。 No unwrap required each time it is used 每次使用时都不需要打开包装
The difference between unowned
and weak
is that weak
is declared as an Optional while unowned
isn't. unowned
weak
的区别在于, weak
被宣告为可选, unowned
被宣告为unowned
。 If you know that self will not be nil
use unowned
, if you don't know: Use weak
如果你知道自己不会是
nil
使用unowned
,如果你不知道:使用weak
Unowned
is used when you 100% sure the object won't be deallocated. Unowned
,当你100%肯定的对象将不会被释放时使用。
weak
you then need to take care of its reference count issues. weak
你然后需要照顾它的引用计数问题。
viewModel.onModelChange = { [weak self] () in
guard let strongSelf = self else { return }
strongSelf.tableView.reloadData()
}
I generally do it like this. 我一般这样做。 You then hold a strong reference of
self
to avoid it being allocated during the block is running. 然后,您可以拥有一个强大的
self
引用,以避免在块运行期间分配它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.