您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

淺談 iOS 的 MVVM 架構設計與團隊協作

編輯:iOS 開發綜合

MVVM 由三個部分組成:Model 負責資料,View 就是 ViewController 及其視圖層,而 ViewModel 是 View 與 Model 之間的黏合劑——使用者輸入驗證、視圖顯示邏輯、網路請求的組織,都應該放在這裡。說穿了,就是把原本堆在 ViewController 裡的業務邏輯與頁面邏輯剝離出去。

為什麼要離開 MVC

如果沒聽過 MVC,那麼你大概聽過另一個說法:Massive View Controller(重量級視圖控制器)。這正是多數 iOS 專案的寫照。回头看,如果當初知道會走到這一步,我會做很不一樣的決策。

典型的 MVC 設置如下:Model 呈現資料,View 呈現使用者介面,ViewController 調解兩者互動。

仔細想想,雖然 View 與 ViewController 在技術上是不同元件,但它們幾乎總是成對出現、手牽手在一起。你什麼時候看過一個 View 搭配不同 ViewController?既然如此,為什麼不把這種綁定關係正式化?

這張圖更貼近我們實際寫出來的 MVC。但它並沒有解決重量級 ViewController 的問題:大量邏輯被塞進 ViewController,其中有些確實屬於它,但更多是所謂的表示邏輯(presentation logic)——把 Model 資料轉換成 View 能呈現的樣子,例如把 NSDate 格式化為 NSString。

我們缺的是一個可以安放這些邏輯的地方。稱它為 View Model:

MVVM 聽起來複雜,本質上就是一個精心優化過的 MVC:把 View 與 Controller 的關係正式化,並把表示邏輯從 Controller 移到一個新物件裡。

三個你應該帶走的重點

  • MVVM 可以兼容你現有的 MVC 架構。
  • MVVM 能顯著提升應用的可測試性。
  • MVVM 搭配一個綁定機制時效果最好。

一、與現有 MVC 共存

先看一個簡單的 Person Model:

@interface Person : NSObject

- (instancetype)initWithSalutation:(NSString *)salutation
                         firstName:(NSString *)firstName
                          lastName:(NSString *)lastName
                         birthdate:(NSDate *)birthdate;

@property (nonatomic, readonly) NSString *salutation;
@property (nonatomic, readonly) NSString *firstName;
@property (nonatomic, readonly) NSString *lastName;
@property (nonatomic, readonly) NSDate *birthdate;

@end

對應的 PersonViewController 在 viewDidLoad 中設置幾個 Label:

- (void)viewDidLoad {
    [super viewDidLoad];

    if (self.model.salutation.length > 0) {
        self.nameLabel.text = [NSString stringWithFormat:@"%@ %@ %@",
                               self.model.salutation, self.model.firstName, self.model.lastName];
    } else {
        self.nameLabel.text = [NSString stringWithFormat:@"%@ %@",
                               self.model.firstName, self.model.lastName];
    }

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"];
    self.birthdateLabel.text = [dateFormatter stringFromDate:self.model.birthdate];
}

標準的 MVC,但表示邏輯已經開始繁殖。現在引入 ViewModel:

@interface PersonViewModel : NSObject

- (instancetype)initWithPerson:(Person *)person;

@property (nonatomic, readonly) Person *person;
@property (nonatomic, readonly) NSString *nameText;
@property (nonatomic, readonly) NSString *birthdateText;

@end
@implementation PersonViewModel

- (instancetype)initWithPerson:(Person *)person {
    self = [super init];
    if (!self) return nil;

    _person = person;

    if (person.salutation.length > 0) {
        _nameText = [NSString stringWithFormat:@"%@ %@ %@",
                     person.salutation, person.firstName, person.lastName];
    } else {
        _nameText = [NSString stringWithFormat:@"%@ %@",
                     person.firstName, person.lastName];
    }

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"];
    _birthdateText = [dateFormatter stringFromDate:person.birthdate];

    return self;
}

@end

於是我們的 viewDidLoad 瞬間變得輕盈:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nameLabel.text = self.viewModel.nameText;
    self.birthdateLabel.text = self.viewModel.birthdateText;
}

架構沒有大改,只是把程式碼搬了位置——這就是 MVVM 容易落地的原因。

二、可測試性

ViewController 出了名地難測,因為它做了太多事。把邏輯移進 ViewModel 之後,測試變得直接:

SpecBegin(Person)

NSString *salutation = @"Dr.";
NSString *firstName  = @"first";
NSString *lastName   = @"last";
NSDate *birthdate    = [NSDate dateWithTimeIntervalSince1970:0];

it(@"should use the salutation available", ^{
    Person *person = [[Person alloc] initWithSalutation:salutation
                                             firstName:firstName
                                              lastName:lastName
                                             birthdate:birthdate];
    PersonViewModel *viewModel = [[PersonViewModel alloc] initWithPerson:person];
    expect(viewModel.nameText).to.equal(@"Dr. first last");
});

it(@"should not use an unavailable salutation", ^{
    Person *person = [[Person alloc] initWithSalutation:nil
                                             firstName:firstName
                                              lastName:lastName
                                             birthdate:birthdate];
    PersonViewModel *viewModel = [[PersonViewModel alloc] initWithPerson:person];
    expect(viewModel.nameText).to.equal(@"first last");
});

it(@"should use the correct date format", ^{
    Person *person = [[Person alloc] initWithSalutation:nil
                                             firstName:firstName
                                              lastName:lastName
                                             birthdate:birthdate];
    PersonViewModel *viewModel = [[PersonViewModel alloc] initWithPerson:person];
    expect(viewModel.birthdateText).to.equal(@"Thursday January 1, 1970");
});

SpecEnd

若邏輯還留在 ViewController,我們就必須實例化完整的 VC 與它的 View 階層,再去比對 Label 的文字——既麻煩又脆弱。現在,我們可以自由重構視圖階層而不擔心弄壞單元測試。

三、綁定機制

上面的例子裡 Model 是不可變的,所以 ViewModel 的屬性可以在初始化時一次決定。但面對可變 Model,就需要綁定機制:Model 變了,ViewModel 要更新自己的屬性;ViewModel 變了,View 也要隨之刷新。變更必須由上而下層層傳遞。

在 OS X 上我們有 Cocoa Bindings;iOS 沒有這麼現成的方案。KVO 可以做到,但即使只是綁一個屬性也要寫不少样板程式碼,屬性一多就難以維護。因此我個人偏好 ReactiveCocoa 這類框架——但請注意,MVVM 並不強制你使用任何特定的綁定庫。MVVM 本身是獨立且完整的模式,只是搭配良好的綁定框架時會更好用。

結語

回顧一下:我們從熟悉的 MVC 出發,把 View 與 Controller 的關係正式化,並將表示邏輯搬到 ViewModel;接著看到它如何兼容既有架構、如何讓測試變得可行,以及在搭配綁定機制時的樣貌。

對團隊而言,MVVM 更大的價值在協作:設計稿的文案與格式化規則集中在 ViewModel,改需求時不必翻遍每個 ViewController;而 ViewModel 可獨立測試,也讓 code review 的邊界變得清楚。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved