
面對 Massive View Controller,目前流行的解法是 MVVM 架構,把業務邏輯遷移到 ViewModel,從而減少 ViewController 中的代碼。
這幾天又看到另一種思路,特此分享。
示例場景
我們用一個例子來說明——這是一個常見的基於 TableView 的界面:通訊錄用戶信息列表。

業務流程
App 啟動後先讀取本地 Core Data 數據並展示,隨後調用 Web API 獲取用戶列表,再更新本地數據庫;一旦數據更新,界面上的展示也隨之變化。此外,用戶也能在本地添加數據,並同步到服務端。
1. 聲明協議
我們不會把全部業務邏輯堆進 ViewController,而是先聲明兩個 protocol。
PeopleListDataProviderProtocol
定義數據源對象需實現的屬性與方法:
public protocol PeopleListDataProviderProtocol: UITableViewDataSource { var managedObjectContext: NSManagedObjectContext? { get set } weak var tableView: UITableView! { get set } func addPerson(personInfo: PersonInfo) func fetch() }APICommunicatorProtocol
定義 API 請求者需實現的屬性與方法:
public protocol APICommunicatorProtocol { func getPeople() -> (NSError?, [PersonInfo]?) func postPerson(personInfo: PersonInfo) -> NSError? }2. 編寫 ViewController
我們的 ViewController 名為 PeopleListViewController,在其中聲明兩個屬性:
public var dataProvider: PeopleListDataProviderProtocol? public var communicator: APICommunicatorProtocol = APICommunicator()
實現 viewDidLoad:
override public func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addPerson") self.navigationItem.rightBarButtonItem = addButton // ViewController 繼承於 UITableViewController assert(dataProvider != nil, "dataProvider is not allowed to be nil at this point") tableView.dataSource = dataProvider dataProvider?.tableView = tableView }添加按鈕的事件響應與回調:
func addPerson() { let picker = ABPeoplePickerNavigationController() picker.peoplePickerDelegate = self presentViewController(picker, animated: true, completion: nil) } extension PeopleListViewController: ABPeoplePickerNavigationControllerDelegate { public func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) { let personInfo = PersonInfo(abRecord: person) dataProvider?.addPerson(personInfo) } }再補上請求與同步數據的兩個方法:
public func fetchPeopleFromAPI() { let allPersonInfos = communicator.getPeople().1 if let allPersonInfos = allPersonInfos { for personInfo in allPersonInfos { dataProvider?.addPerson(personInfo) } } } public func sendPersonToAPI(personInfo: PersonInfo) { communicator.postPerson(personInfo) }至此,ViewController 全部完成,僅 60 行代碼,是不是清爽多了?
那 Web API 調用、Core Data 操作、業務邏輯的代碼都去哪了?接下來,我們就來實現那兩個協議。
3. 實現 Protocol
先實現 APICommunicatorProtocol 的 APICommunicator 類:
public struct APICommunicator: APICommunicatorProtocol { public func getPeople() -> (NSError?, [PersonInfo]?) { return (nil, nil) } public func postPerson(personInfo: PersonInfo) -> NSError? { return nil } }與服務端的交互這裡先略去,做個簡單實現即可。
再看實現了 PeopleListDataProviderProtocol 的 PeopleListDataProvider 類,主要包含以下幾部分。
Core Data 操作:
public func fetch() { let sortKey = NSUserDefaults.standardUserDefaults().integerForKey("sort") == 0 ? "lastName" : "firstName" let sortDescriptor = NSSortDescriptor(key: sortKey, ascending: true) let sortDescriptors = [sortDescriptor] fetchedResultsController.fetchRequest.sortDescriptors = sortDescriptors var error: NSError? = nil do { try fetchedResultsController.performFetch() } catch let error1 as NSError { error = error1 print("error: \(error)") } tableView.reloadData() }UITableViewDataSource 的實現:
public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let person = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Person cell.textLabel!.text = person.fullname cell.detailTextLabel!.text = dateFormatter.stringFromDate(person.birthday) }NSFetchedResultsControllerDelegate 的實現:
public func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } }(未列出全部代碼)
可以看到,我們把業務邏輯都放進了 PeopleListDataProviderProtocol 和 APICommunicatorProtocol 的實現中;ViewController 通過屬性引用這兩個協議的實現類,並調用協議中定義的方法。
優勢
ViewController 的代碼變得短小而清晰。
與 MVVM 一樣,實現了界面與業務邏輯的分離。
相比 MVVM,學習成本更低。
方便創建 Mock 對象。
Mock 對象
例如這個 APICommunicator:
public var communicator: APICommunicatorProtocol = APICommunicator()
在開發過程中或單元測試時,都可以用一個 MockAPICommunicator 來替代它,提供假數據。
class MockAPICommunicator: APICommunicatorProtocol { var allPersonInfo = [PersonInfo]() var postPersonGotCalled = false func getPeople() -> (NSError?, [PersonInfo]?) { return (nil, allPersonInfo) } func postPerson(personInfo: PersonInfo) -> NSError? { postPersonGotCalled = true return nil } }這樣,在服務端 API 尚未部署時,我們可以用假數據方便地推進功能開發,等 API 上線後再換回真正的 APICommunicator。同樣,也可以提供一個實現了 PeopleListDataProviderProtocol 的 MockDataProvider 類,並借用 Mock 對象進行單元測試。例如:
func testFetchingPeopleFromAPICallsAddPeople() { // given let mockDataProvider = MockDataProvider() viewController.dataProvider = mockDataProvider let mockCommunicator = MockAPICommunicator() mockCommunicator.allPersonInfo = [PersonInfo(firstName: "firstname", lastName: "lastname", birthday: NSDate())] viewController.communicator = mockCommunicator // when viewController.fetchPeopleFromAPI() // then XCTAssertTrue(mockDataProvider.addPersonGotCalled, "addPerson should have been called") }總結
MVVM 的優勢在於較為普及,是大家都懂的通用模式,能降低溝通成本;但響應式編程、事件管道、ReactiveCocoa 等概念仍有一定學習門檻。在不採用 MVVM 的情況下,不妨試試本文介紹的結構,同樣能為 ViewController 瘦身。
參考資料:
https://www.raywenderlich.com/101306/unit-testing-tutorial-mocking-objects
源碼下載:
https://cdn2.raywenderlich.com/wp-content/uploads/2015/04/Birthdays_Final1.zip