使用rxSwift绑定数据时发生内存泄漏

时间:2017-04-05 19:17:57

标签: swift xcode memory-leaks instruments rx-swift

当我尝试使用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)
    }
}

你知道为什么这个内存泄漏会自行创建,我该如何避免它呢?

1 个答案:

答案 0 :(得分:0)

func bindDataWithViewModel() {

    if let viewModel = viewControllerViewModel {
        locationTextField.rx.text.orEmpty
            .bindTo(viewModel.location)
            .addDisposableTo(disposeBag) // use addDisposableTo
    }
}