当我尝试使用UITextField
绑定我ViewController
中的var location = Variable<String?>("")
变量ViewControllerViewModel
rxSwift
时,我收到了有关的信息内存泄漏。我喜欢这样:
我的ViewController
class ViewController {
@IBOutlet weak var locationTextField: UITextField!
var viewControllerViewModel: ViewControllerViewModel?
lazy var disposeBag = DisposeBag()
/*
Another variables etc.
*/
override func viewDidLoad() {
super.viewDidLoad()
bindDataWithViewModel()
}
func bindDataWithViewModel() {
if let viewModel = viewControllerViewModel {
locationTextField.rx.text.bindTo(viewModel.location).disposed(by: disposeBag) -> // here shows memory leak
}
}
}
我的ViewControllerViewModel
class ViewControllerViewModel {
var location = Variable<String?>("")
var infoStruct = InfoStruct()
lazy var disposeBag = DisposeBag()
init() {
initValueObservable()
}
func initValueObservable() {
location.asObservable().subscribe(onNext: { [unowned self] text in
self.infoStruct.location = text
}).addDisposableTo(disposeBag)
}
}
你知道为什么这个内存泄漏会自行创建,我该如何避免它呢?
答案 0 :(得分:0)
func bindDataWithViewModel() {
if let viewModel = viewControllerViewModel {
locationTextField.rx.text.orEmpty
.bindTo(viewModel.location)
.addDisposableTo(disposeBag) // use addDisposableTo
}
}