在MVVM中嫩挤,由于ViewController持有ViewModel籽御,而ViewModel不能反向持有ViewController,所以贴浙,當(dāng)ViewModel中發(fā)生變化時,需要通知ViewController署恍,所以需要將ViewModel中的一些內(nèi)容與ViewController綁定起來崎溃,這稱為單向綁定;有時ViewController和viewModel中任何一端發(fā)生變化锭汛,對方都能知道笨奠,這稱為雙向綁定袭蝗。ViewModel與Model之間的關(guān)系同理。
單向綁定
/// Examples
///
/// RAC(self, objectProperty) = objectSignal;
通常用RAC宏來實現(xiàn)屬性objectProperty與信號objectSignal的綁定般婆,而objectSignal通常用RACObserve這個宏來創(chuàng)建到腥。
/// Creates a signal which observes `KEYPATH` on `TARGET` for changes.
/// // Observes self, and doesn't stop until self is deallocated.
/// RACSignal *selfSignal = RACObserve(self, arrayController.items);
///
/// // Observes the array controller, and stops when self _or_ the array
/// // controller is deallocated.
/// RACSignal *arrayControllerSignal = RACObserve(self.arrayController, items);
在單向綁定中,通常這么使用:
RAC(self, vcProperty) = RACObserve(self.viewModel, vmProperty);
雙向綁定
RACChannelTo(self.textField, text) = RACChannelTo(self.viewModel, someProperty)
RACChannelTo()當(dāng)被用作表達式時蔚袍,返回RACChannelTerminal乡范,可以用來監(jiān)控屬性的變化;當(dāng)RACChannelTo()放在等號左側(cè)時啤咽,右側(cè)表達式必須是RACChannelTerminal晋辆,這時兩邊會相互訂閱:兩邊的屬性變化會反應(yīng)到另一端。