Lighter View Controllers

View controllers are often the biggest files in iOS projects, and they often contain way more code than necessary. Almost always, view controllers are the least reusable part of the code. We will look at techniques to slim down your view controllers, make code reusable, and move code to more appropriate places.

The example project for this issue is on GitHub.

Separate Out Data Source and Other Protocols

One of the most powerful techniques to slim down your view controller is to take the UITableViewDataSource part of your code, and move it to its own class. If you do this more than once, you will start to see patterns and create reusable classes for this.

For example, in our example project, there is a class PhotosViewControllerwhich had the following methods:

- (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:PhotoCellIdentifier 
                                                      forIndexPath:indexPath];
    Photo* photo = [self photoAtIndexPath:indexPath];
    cell.label.text = photo.name;
    return cell;
}

A lot of this code has to do with arrays, and some of it is specific to the photos that the view controller manages. So let’s try to move the array-related code into its own class. We use a block for configuring the cell, but it might as well be a delegate, depending on your use-case and taste.

- (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:cellIdentifier
                                              forIndexPath:indexPath];
    id item = [self itemAtIndexPath:indexPath];
    configureCellBlock(cell,item);
    return cell;
}

@end

The three methods that were in your view controller can go, and instead you can create an instance of this object and set it as the table view’s data source.

void (^configureCell)(PhotoCell*, Photo*) = ^(PhotoCell* cell, Photo* photo) {
   cell.label.text = photo.name;
};
photosArrayDataSource = [[ArrayDataSource alloc] initWithItems:photos
                                                cellIdentifier:PhotoCellIdentifier
                                            configureCellBlock:configureCell];
self.tableView.dataSource = photosArrayDataSource;

Now you don’t have to worry about mapping an index path to a position in the array, and every time you want to display an array in a table view you can reuse this code. You can also implement additional methods such as tableView:commitEditingStyle:forRowAtIndexPath: and share that code among all your table view controllers.

The nice thing is that we can test this class separately, and never have to worry about writing it again. The same principle applies if you use something else other than arrays.

In one of the applications we were working on this year, we made heavy use of Core Data. We created a similar class, but instead of being backed by an array, it is backed by a fetched results controller. It implements all the logic for animating the updates, doing section headers, and deletion. You can then create an instance of this object and feed it a fetch request and a block for configuring the cell, and the rest will be taken care of.

Furthermore, this approach extends to other protocols as well. One obvious candidate is UICollectionViewDataSource. This gives you tremendous flexibility; if, at some point during the development, you decide to have a UICollectionView instead of a UITableView, you hardly have to change anything in your view controller. You could even make your data source support both protocols.

Move Domain Logic into the Model

Here is an example of code in view controller (from another project) that is supposed to find a list of active priorities for a user:

- (void)loadPriorities {
  NSDate* now = [NSDate date];
  NSString* formatString = @"startDate <= %@ AND endDate >= %@";
  NSPredicate* predicate = [NSPredicate predicateWithFormat:formatString, now, now];
  NSSet* priorities = [self.user.priorities filteredSetUsingPredicate:predicate];
  self.priorities = [priorities allObjects];
}

However, it is much cleaner to move this code to a category on the User class. Then it looks like this in View Controller.m:

- (void)loadPriorities {
  self.priorities = [self.user currentPriorities];
}

and in User+Extensions.m:

- (NSArray*)currentPriorities {
  NSDate* now = [NSDate date];
  NSString* formatString = @"startDate <= %@ AND endDate >= %@";
  NSPredicate* predicate = [NSPredicate predicateWithFormat:formatString, now, now];
  return [[self.priorities filteredSetUsingPredicate:predicate] allObjects];
}

Some code cannot be easily moved into a model object but is still clearly associated with model code, and for this, we can use a Store:

Creating the Store Class

In the first version of our example application, we had some code to load data from a file and parse it. This code was in the 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];
}

The view controller should not have to know about this. We created a Store object that does just this. By separating it out, we can reuse that code, test it separately and keep our view controller small. The store can take care of data loading, caching, and setting up the database stack. This store is also often called a service layer or a repository.

Move Web Service Logic to the Model Layer

This is very similar to the topic above: don’t do web service logic in your view controller. Instead, encapsulate this in a different class. Your view controller can then call methods on this class with a callback handler (for example, a completion block). The nice thing is that you can do all your caching and error handling in this class too.

Move View Code into the View Layer

Building complicated view hierarchies shouldn’t be done in view controllers. Either use interface builder, or encapsulate views into their own UIView subclasses. For example, if you build your own date picker control, it makes more sense to put this into a DatePickerView class than creating the whole thing in the view controller. Again, this increases reusability and simplicity.

If you like Interface Builder, then you can also do this in Interface Builder. Some people assume you can only use this for view controllers, but you can also load separate nib files with your custom views. In our example app, we created a PhotoCell.xib that contains the layout for a photo cell:

PhotoCell.xib screenshot

As you can see, we created properties on the view (we don’t use the File’s Owner object in this xib) and connect them to specific subviews. This technique is also very handy for other custom views.

Communication

One of the other things that happen a lot in view controllers is communication with other view controllers, the model, and the views. While this is exactly what a controller should do, it is also something we’d like to achieve with as minimal code as possible.

There are a lot of well-explained techniques for communication between your view controllers and your model objects (such as KVO and fetched results controllers), however, communication between view controllers is often a bit less clear.

We often have the problem where one view controller has some state and communicates with multiple other view controllers. Often, it then makes sense to put this state into a separate object and pass it around the view controllers, which then all observe and modify that state. The advantage is that it’s all in one place, and we don’t end up entangled in nested delegate callbacks. This is a complex subject, and we might dedicate a whole issue to this in the future.

Conclusion

We’ve seen some techniques for creating smaller view controllers. We don’t strive to apply these techniques wherever possible, as we have only one goal: to write maintainable code. By knowing these patterns, we have better chances of taking unwieldy view controllers and making them clearer.

Further Reading

轉(zhuǎn)載:https://www.objc.io/issues/1-view-controllers/lighter-view-controllers/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末盯质,一起剝皮案震驚了整個(gè)濱河市肌毅,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,743評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)孕似,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,296評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來刮刑,“玉大人喉祭,你說我怎么就攤上這事±拙睿” “怎么了泛烙?”我有些...
    開封第一講書人閱讀 157,285評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)翘紊。 經(jīng)常有香客問我蔽氨,道長(zhǎng),這世上最難降的妖魔是什么帆疟? 我笑而不...
    開封第一講書人閱讀 56,485評(píng)論 1 283
  • 正文 為了忘掉前任鹉究,我火速辦了婚禮,結(jié)果婚禮上踪宠,老公的妹妹穿的比我還像新娘自赔。我一直安慰自己,他們只是感情好柳琢,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,581評(píng)論 6 386
  • 文/花漫 我一把揭開白布绍妨。 她就那樣靜靜地躺著润脸,像睡著了一般。 火紅的嫁衣襯著肌膚如雪他去。 梳的紋絲不亂的頭發(fā)上津函,一...
    開封第一講書人閱讀 49,821評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音孤页,去河邊找鬼。 笑死涩馆,一個(gè)胖子當(dāng)著我的面吹牛行施,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播魂那,決...
    沈念sama閱讀 38,960評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼蛾号,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了涯雅?” 一聲冷哼從身側(cè)響起鲜结,我...
    開封第一講書人閱讀 37,719評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎活逆,沒想到半個(gè)月后精刷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,186評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蔗候,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,516評(píng)論 2 327
  • 正文 我和宋清朗相戀三年怒允,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片锈遥。...
    茶點(diǎn)故事閱讀 38,650評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡纫事,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出所灸,到底是詐尸還是另有隱情丽惶,我是刑警寧澤,帶...
    沈念sama閱讀 34,329評(píng)論 4 330
  • 正文 年R本政府宣布爬立,位于F島的核電站钾唬,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏懦尝。R本人自食惡果不足惜知纷,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,936評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望陵霉。 院中可真熱鬧琅轧,春花似錦、人聲如沸踊挠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,757評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至睹酌,卻和暖如春权谁,著一層夾襖步出監(jiān)牢的瞬間即横,已是汗流浹背丢烘。 一陣腳步聲響...
    開封第一講書人閱讀 31,991評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工躬厌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留集灌,地道東北人璃吧。 一個(gè)月前我還...
    沈念sama閱讀 46,370評(píng)論 2 360
  • 正文 我出身青樓作喘,卻偏偏與公主長(zhǎng)得像惧笛,于是被迫代替她去往敵國(guó)和親仲翎。 傳聞我的和親對(duì)象是個(gè)殘疾皇子壶辜,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,527評(píng)論 2 349