天天看點

更輕量的 View Controllers

View controllers 通常是 iOS 項目中最大的檔案,并且它們包含了許多不必要的代碼。是以 View controllers 中的代碼幾乎總是複用率最低的。我們将會看到給 view controllers 瘦身的技術,讓代碼變得可以複用,以及把代碼移動到更合适的地方。

你可以在 Github 上擷取關于這個問題的示例項目。

把 Data Source 和其他 Protocols 分離出來

把 

UITableViewDataSource

 的代碼提取出來放到一個單獨的類中,是為 view controller 瘦身的強大技術之一。當你多做幾次,你就能總結出一些模式,并且建立出可複用的類。

舉個例,在示例項目中,有個 

PhotosViewController

 類,它有以下幾個方法:

# pragma mark Pragma



- (Photo\*)photoAtIndexPath:(NSIndexPath\*)indexPath {

    return photos[(NSUInteger)indexPath.row];

}



- (NSInteger)tableView:(UITableView\*)tableView

 numberOfRowsInSection:(NSInteger)section {

    return photos.count;

}



- (UITableViewCell\*)tableView:(UITableView\*)tableView

        cellForRowAtIndexPath:(NSIndexPath\*)indexPath {

    PhotoCell\* cell = [tableView dequeueReusableCellWithIdentifier:PhotoCellIdentifie

                                                      forIndexPath:indexPath];

    Photo\* photo = [self photoAtIndexPath:indexPath];

    cell.label.text = photo.name;

    return cell;

}           

複制

這些代碼基本都是圍繞數組做一些事情,更針對地說,是圍繞 view controller 所管理的 photos 數組做一些事情。我們可以嘗試把數組相關的代碼移到單獨的類中。我們使用一個 block 來設定 cell,也可以用 delegate 來做這件事,這取決于你的習慣。

@implementation ArrayDataSource



- (id)itemAtIndexPath:(NSIndexPath\*)indexPath {

    return items[(NSUInteger)indexPath.row];

}



- (NSInteger)tableView:(UITableView\*)tableView

 numberOfRowsInSection:(NSInteger)section {

    return items.count;

}



- (UITableViewCell\*)tableView:(UITableView\*)tableView

        cellForRowAtIndexPath:(NSIndexPath\*)indexPath {

    id cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifie

                                              forIndexPath:indexPath];

    id item = [self itemAtIndexPath:indexPath];

    configureCellBlock(cell,item);

    return cell;

}



@end           

複制

現在,你可以把 view controller 中的這 3 個方法去掉了,取而代之,你可以建立一個 ArrayDataSource 類的執行個體作為 table view 的 data source。

void (^configureCell)(PhotoCell\*, Photo\*) = ^(PhotoCell\* cell, Photo\* photo) {

   cell.label.text = photo.name;

};

photosArrayDataSource = [[ArrayDataSource alloc] initWithItems:photos

                                                cellIdentifier:PhotoCellIdentifie

                                            configureCellBlock:configureCell];

self.tableView.dataSource = photosArrayDataSource;           

複制

現在你不用擔心把一個 index path 映射到數組中的位置了,每次你想把這個數組顯示到一個 table view 中時,你都可以複用這些代碼。你也可以實作一些額外的方法,比如 

tableView:commitEditingStyle:forRowAtIndexPath:

,在 table view controllers 之間共享。

這樣的好處在于,你可以單獨測試這個類,再也不用寫第二遍。該原則同樣适用于數組之外的其他對象。

在今年我們做的一個應用裡面,我們大量使用了 Core Data。我們建立了相似的類,但和之前使用的數組不一樣,它用一個 fetched results controller 來擷取資料。它實作了所有動畫更新、處理 section headers、删除操作等邏輯。你可以建立這個類的執行個體,然後賦予一個 fetch request 和用來設定 cell 的 block,剩下的它都會處理,不用你操心了。

此外,這種方法也可以擴充到其他 protocols 上面。最明顯的一個就是 

UICollectionViewDataSource

。這給了你極大的靈活性;如果,在開發的某個時候,你想用 

UICollectionView

 代替 

UITableView

,你幾乎不需要對 view controller 作任何修改。你甚至可以讓你的 data source 同時支援這兩個協定。

将業務邏輯移到 Model 中

下面是 view controller(來自其他項目)中的示例代碼,用來查找一個使用者的目前的優先事項的清單:

- (void)loadPriorities {

    NSDate\* now = [NSDate date];

    NSString\* formatString = @"startDate = %@";

    NSPredicate\* predicate = [NSPredicate predicateWithFormat:formatString, now, now];

    NSSet\* priorities = [self.user.priorities filteredSetUsingPredicate:predicate];

    self.priorities = [priorities allObjects];

}           

複制

把這些代碼移動到

User

類的 category 中會變得更加清晰,處理之後,在

View Controller.m

中看起來就是這樣:

- (void)loadPriorities {

    self.priorities = [user currentPriorities];

}           

複制

User+Extensions.m

中:

- (NSArray\*)currentPriorities {

    NSDate\* now = [NSDate date];

    NSString\* formatString = @"startDate = %@";

    NSPredicate\* predicate = [NSPredicate predicateWithFormat:formatString, now, now];

    return [[self.priorities filteredSetUsingPredicate:predicate] allObjects];

}           

複制

建立 Store 類

在我們第一版的示例程式的中,有些代碼去加載檔案并解析它。下面就是 view controller 中的代碼:

- (void)readArchive {

    NSBundle\* bundle = [NSBundle bundleForClass:[self class]];

    NSURL \*archiveURL = [bundle URLForResource:@"photodata"

                                 withExtension:@"bin"];

    NSAssert(archiveURL != nil, @"Unable to find archive in bundle.");

    NSData \*data = [NSData dataWithContentsOfURL:archiveURL

                                         options:0

                                           error:NULL];

    NSKeyedUnarchiver \*unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    \_users = [unarchiver decodeObjectOfClass:[NSArray class] forKey:@"users"];

    \_photos = [unarchiver decodeObjectOfClass:[NSArray class] forKey:@"photos"];

    [unarchiver finishDecoding];

}           

複制

但是 view controller 沒必要知道這些,是以我們建立了一個 *Store* 對象來做這些事。通過分離,我們就可以複用這些代碼,單獨測試他們,并且讓 view controller 保持小巧。Store 對象會關心資料加載、緩存和設定資料棧。它也經常被稱為服務層或者倉庫。

把網絡請求邏輯移到 Model 層

和上面的主題相似:不要在 view controller 中做網絡請求的邏輯。取而代之,你應該将它們封裝到另一個類中。這樣,你的 view controller 就可以在之後通過使用回調(比如一個 completion 的 block)來請求網絡了。這樣的好處是,緩存和錯誤控制也可以在這個類裡面完成。

把 View 代碼移到 View 層

不應該在 view controller 中建構複雜的 view 層次結構。你可以使用 Interface Builder 或者把 views 封裝到一個 

UIView

 子類當中。例如,如果你要建立一個選擇日期的控件,把它放到一個名為 

DatePickerView

 的類中會比把所有的事情都在 view controller 中做好好得多。再一次,這樣增加了可複用性并保持了簡單。

如果你喜歡 Interface Builder,你也可以在 Interface Builder 中做。有些人認為 IB 隻能和 view controllers 一起使用,但事實上你也可以加載單獨的 nib 檔案到自定義的 view 中。在示例程式中,我們建立了一個 

PhotoCell.xib

,包含了 photo cell 的布局:

更輕量的 View Controllers

就像你看到的那樣,我們在 view(我們沒有在這個 nib 上使用 File's Owner 對象)上面建立了 properties,然後連接配接到指定的 subviews。這種技術同樣适用于其他自定義的 views。

通訊

其他在 view controllers 中經常發生的事是與其他 view controllers,model,和 views 之間進行通訊。這當然是 controller 應該做的,但我們還是希望以盡可能少的代碼來完成它。

關于 view controllers 和 model 對象之間的消息傳遞,已經有很多闡述得很好的技術(比如 KVO 和 fetched results controllers)。但是 view controllers 之間的消息傳遞稍微就不是那麼清晰了。

當一個 view controller 想把某個狀态傳遞給多個其他 view controllers 時,就會出現這樣的問題。較好的做法是把狀态放到一個單獨的對象裡,然後把這個對象傳遞給其它 view controllers,它們觀察和修改這個狀态。這樣的好處是消息傳遞都在一個地方(被觀察的對象)進行,而且我們也不用糾結嵌套的 delegate 回調。這其實是一個複雜的主題,我們可能在未來用一個完整的話題來讨論這個主題。

總結

我們已經看到一些用來建立更小巧的 view controllers 的技術。我們并不是想把這些技術應用到每一個可能的角落,隻是我們有一個目标:寫可維護的代碼。知道這些模式後,我們就更有可能把那些笨重的 view controllers 變得更整潔。