ViewController规范化写法

1、ViewController代码布局

在一个规范的开发团队中,在代码规范上应该达到每一个程序员所写出来的ViewController结构一致的目标,这样的规范能减少各种delegate getter随机出现,ViewController lifecycle方法到处都是。制定一个规范,可以使代码更有利于阅读和维护,当然,规范的制定和团队的架构师的经验而定。
OS应用架构谈 view层的组织和调用方案这篇文章里提供一个布局规范,如下图所示:
clipboard.png

此外,所有需要初始化的属性可以放在getter方法中。

#pragma mark - life cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.firstTableView];
    [self.view addSubview:self.secondTableView];
    [self.view addSubview:self.firstFilterLabel];
    [self.view addSubview:self.secondFilterLabel];
    [self.view addSubview:self.cleanButton];
    [self.view addSubview:self.originImageView];
    [self.view addSubview:self.processedImageView];
    [self.view addSubview:self.activityIndicator];
    [self.view addSubview:self.takeImageButton];
}

避免出现以下这种情况

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.textLabel = [[UILabel alloc] init];
    self.textLabel.textColor = [UIColor blackColor];
    self.textLabel ... ...
    self.textLabel ... ...
    self.textLabel ... ...
    [self.view addSubview:self.textLabel];
}

一般情况下,View的创建是应该放在View中处理。这两种初始化方式相比,很明显第一种比较简洁,将初始化放到getter中,分工明确,也有利于做测试。

2、轻量化ViewController

在ios的开发中,MVC的核心就在ViewController,有些开发人员在不熟悉MVC的情况下,把所有东西统统放入C里面就可以了,所以往往一个ViewController既有View的创建,也会有Model里的业务逻辑。这样一个臃肿的ViewController不好阅读,不好维护,更不利于做单元测试。
Lighter View Controllers文章里提出了几个应该属于ViewController规范化问题的概念。

2.1、将DataSource和其他Protocols隔离

精简 ViewController 的有效方法之一就是实现 UITableViewDataSource 协议相关的代码封装成一个类(比如本文中的 ArraryDataSource )。如果你经常在 UIViewController 中实现 UITableViewDataSource 协议,你会发现相关代码看起来都差不多。

举例说明:

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

可以看到上面方法的实现都与 NSArray 有关,还有一个方法的实现与 Photo 有关(Photo 与 Cell 呈一一对应关系)。下面让我们来把与 NSArray 相关的代码从 ViewController 中抽离出来,并改用 block 来设置 cell 的视图。

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

@end

现在你可以把 ViewController 中的相关方法移除,并且把 ViewController 的 dataSource 设置为 ArrayDataSource 的实例。

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;

通过上面的方法,你就可以把设置 Cell 视图的工作从 ViewController 中抽离出来。现在你不需要再关心indexPath如何与 NSArrary 中的元素如何关联,当你需要将数组中的元素在其它 UITableView 中展示时你可以重用以上代码。你也可以在 ArrayDataSource 中实现更多的方法,比如tableView:commitEditingStyle:forRowAtIndexPath:

除了以上好处之外,我们还可以针对这部分实现编写单独的单元测试,而且再也不需要到处复制粘贴了。当你使用其他数据容器时,你可以用类似的方式来达到代码复用的效果。

该技巧同样适用于其他 Protocol ,比如 UICollectionViewDataSource 。通过该协议,你可以定义出各种各样的 UICollectionViewCell 。假如有一天,你需要在代码在使用到 UICollectionView 来替代当前的 UITableView,你只需要修改几行 ViewController 中的代码即可完成替换。你甚至能够让你的 DataSource 类同时实现 UICollectionViewDataSource 协议和 UITableViewDataSource 协议。

除此之外,还有很多关于这个方面的讨论:
UITableview代理方法与Viewcontroller分离
不要把 ViewController 变成处理 tableView 的"垃圾桶"

2.2、将业务逻辑移至Model层

下面的示例代码(另外一个工程)位于view controller,作用是找出针对用户active priority的一个列表。

- (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]; 
} 

实际上,如果把这个方法移至User类的一个category中,会让代码更加清晰。此时,在View Controller.m文件中看起来应该是这样的:

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

而在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];
}

实际开发中,有一些代码很难将其移至model对象中,但是,很明显这些代码与model是相关的,针对这样的情况,我们可以单独为其写一个类,例如下面的store类。

创建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中剥离出来,不仅可以对其重用和单独测试,另外还能对view controller瘦身。Store类专注于数据的加载、缓存,以及对数据库进行配置。这里的Store也经常叫做service layer或者repository。

2.3、其他轻量化规范

  1. 将网络请求相关逻辑放到Model层处理

  2. View的创建放到View层处理

3、采用比较清晰的架构

如何给UIViewController瘦身这篇文章非常详细的介绍了臃肿的VC会导致什么问题的出现,同时也提出一个非常清晰的架构图,如下:

clipboard.png

4、总结

只有开发人员在完全遵守架构规范进行开发时,架构规范的优势才能完全体现出来。评判一个好的规范的标准很简单,按照规范写出来的代码是否易于阅读、维护、扩展、测试。往往一个成熟的代码规范不是一蹴而就的,需要在实际的开发过程中,不断的去修改完善。但是最重要的一点,适合自己的才是最好的!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值