2017-04-05 49 views
2

結合數據當試圖結合我UITextField這是在我的ViewController具有可變var location = Variable<String?>("")這是我的ViewControllerViewModel使用rxSwift在我收到關於內存泄漏的信息。我這樣做波紋管:內存泄漏,同時用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
func bindDataWithViewModel() { 

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

'addDisposableTo'是一個不推薦的方法 –