MVVM Tutorial with ReactiveCocoa筆記

  1. MVVM架構(gòu)的核心是View-Model,View-Model是一種特殊的Model,它代表了應(yīng)用UI的各種狀態(tài).
    它包含了描述各種UI管理的狀態(tài)的屬性.例如一個(gè)TextField中當(dāng)前的text,一個(gè)button是否是enable狀態(tài).同時(shí)它也向外界提供當(dāng)前View可以執(zhí)行的action,例如button的點(diǎn)擊和手勢(shì)的觸發(fā).

  2. MVVM需要遵循以下規(guī)則

  • View持有ViewModel,但是反過來不可以
  • ViewModel持有Model,但是反過來不可以
  1. 這個(gè)模式最直接的好處如下:
  • 輕量級(jí)的View --- 因?yàn)樗械腢I邏輯都存在于ViewModel中,所以View會(huì)非常輕量級(jí)
  • 測(cè)試 --- 可以再?zèng)]有不依賴View的情況下運(yùn)行程序,極大增強(qiáng)了可測(cè)試性
  1. MVVM架構(gòu)依賴于數(shù)據(jù)綁定,并且是雙向的數(shù)據(jù)綁定,ViewModel的屬性發(fā)生了變化要傳遞給UI,UI上用戶輸入了變化也要傳遞給ViewModel.

  2. UIButton的rac_command屬性跟RACCommand實(shí)例綁定后,可以控制UIButton的enable狀態(tài),同時(shí),點(diǎn)擊UIButton的時(shí)候執(zhí)行該command(validSearchSignal傳遞YES的時(shí)候button可點(diǎn)擊,傳遞NO的時(shí)候Button不可點(diǎn)擊)

[[RACCommand alloc] initWithEnabled:validSearchSignal
    signalBlock:^RACSignal *(id input) {
      return  [self executeSearchSignal];
    }];

self.searchButton.rac_command = self.viewModel.executeSearch;
  1. RACCommand的executing屬性可以用來判斷當(dāng)前的command是否正在執(zhí)行

  2. not方法可以將RACSignal中傳遞的值取反

  3. RACCommand的executionSignals屬性會(huì)把每次command執(zhí)行的時(shí)候創(chuàng)建的signal傳出來(如果command綁定的button,并且點(diǎn)擊button的時(shí)候需要做一些操作,可以用這個(gè)屬性)

[self.viewModel.executeSearch.executionSignals
  subscribeNext:^(id x) {
    [self.searchTextField resignFirstResponder];
  }];
  1. The ViewModel exposes properties that represent the UI state, it also exposes commands — and often methods — that represent UI actions. It’s responsible for managing changes to the UI state based on user interactions.
    However, it’s not responsible for the actual business logic that executes because of these interactions. That is the job of the Model.
  2. MVVM結(jié)構(gòu)總結(jié)

1.model層提供服務(wù)和業(yè)務(wù)邏輯,在Flickr這個(gè)例子里,model層提供Flickr搜索照片的服務(wù)

  1. View-Model層代表了整個(gè)應(yīng)用UI的各種狀態(tài),同時(shí)它也對(duì)用戶交互和和來自Model層的事件進(jìn)行回應(yīng)(UI狀態(tài)的改變).
  2. View層功能非常簡(jiǎn)單,它只提供View-Model層各種狀態(tài)的展示和用戶交互.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容