前言
好孕帮APP截止到现在已经更新过数十个版本,随着需求的增多和功能的变化,原有的架构已经不再适合现有的业务逻辑。原架构采用MVC的设计模式,大量的代码都放在了ViewController中,有的ViewController中的代码甚至达到了2000多行,导致MVC最终演变成了Massive View Controller。本次重构旨在解决以下问题,以期在以后的开发中能保证代码质量,降低维护成本。
1、ViewController中代码过于臃肿;
2、代码书写不规范;
3、缺少缓存及热更新策略;
4、功能相近的三方库的引用;
设计模式
在传统的MVC设计模式中M负责数据封装,View负责数据的展示,像网络请求、数据缓存及大量的胶水代码都放在了Viewcontroller中,导致Viewcontroller越来越臃肿。MVP中新增了Presenter层负责网络请求及数据缓存,减轻Viewcontroller的负担。
MVC、MVP、MVVM模式的比较链接1 链接2
M层
数据组装及一些简单的数据处理,如时间戳转时间
#import "PostDetailModel.h"
@implementation PostDetailModel
+ (instancetype)postDetailModelWithDict:(NSDictionary *)dict {
return [[PostDetailModel alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict {
self = [super init];
if (self) {
NSDictionary *authorDict = [dict objectForKey:@"author"];
self.avatarUrl = [authorDict objectForKey:@"avatar"];
self.contentStr = [dict objectForKey:@"content"];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self.avatarUrl = [aDecoder decodeObjectForKey:@"avatarUrl"];
self.contentStr = [aDecoder decodeObjectForKey:@"contentStr"];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.avatarUrl forKey:@"avatarUrl"];
[aCoder encodeObject:self.contentStr forKey:@"contentStr"];
}
@end
View层
数据展示、点击事件的传递
//PostDetailTableViewCell.h
@interface PostDetailTableViewCell : UITableViewCell
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@property (nonatomic, strong) PostDetailModel *detailModel;
@end
//PostDetailTableViewCell.m
- (void)setDetailModel:(PostDetailModel *)detailModel {
_detailModel = detailModel;
self.contentLabel.text = detailModel.contentStr;
[self.avatarImageView setImageWithURL:[NSURL URLWithString:detailModel.avatarUrl]];
}
Presenter层
数据获取及数据缓存,数据缓存采用YYCache
//PostDetailPresenter.h
@class PostDetailPresenter;
@protocol PostDetailPresenterDelegate
- (void)presenter:(PostDetailPresenter *)presenter status:(ResponseStatusModel *)statusModel error:(NSError *)error;
@end
@interface PostDetailPresenter : NSObject
@property (nonatomic, weak) id delegate;
@property (nonatomic, strong) NSMutableArray *detailArray;
- (void)loadListData;
@end
//PostDetailPresenter.m
- (void)loadListData {
@weakify(self)
[NetworkManager postUrl:@"topic/info/58f821feee07cf0007f3bafb" type:NetWorkTypeForum params:self.requestParams callBack:^(id content, NSError *error) {
@strongify(self)
ResponseStatusModel *statusModel = [ResponseStatusModel modelWithDictionary:content];
if (!error) {
if (statusModel.status == 1) {
NSDictionary *dataDict = [content objectForKey:@"data"];
NSArray *replyArray = [dataDict objectForKey:@"replies"];
if (_refreshHead) {
[self.detailArray removeAllObjects];
}
NSMutableArray *dataArray = [NSMutableArray array];
for (NSDictionary *dict in replyArray) {
PostDetailModel *postDetailModel = [PostDetailModel postDetailModelWithDict:dict];
[dataArray addObject:postDetailModel];
}
if (dataArray.count > 0) {
[self.detailArray addObjectsFromArray:dataArray];
[self.cache setObject:dataArray forKey:[NSString stringWithFormat:@"PostDetailReplyCache%ld",_pageIndex]];
}
_pageIndex++;
}
} else {
if (_refreshHead) {
[self.detailArray removeAllObjects];
}
NSString *key = [NSString stringWithFormat:@"PostDetailReplyCache%ld",_pageIndex];
if ([self.cache containsObjectForKey:key]) {
NSArray *cacheArray = (NSArray *)[self.cache objectForKey:key];
[self.detailArray addObjectsFromArray:cacheArray];
}
_pageIndex++;
}
if (self.delegate && [self.delegate respondsToSelector:@selector(presenter:status:error:)]) {
[self.delegate presenter:self status:statusModel error:error];
}
}];
}
Viewcontroller层
View、Presenter初始化,点击事件跳转处理等等
- (instancetype)init {
self = [super init];
if (self) {
self.presenter = [[PostDetailPresenter alloc] init];
self.presenter.delegate = self;
}
return self;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PostDetailTableViewCell *detailCell = [PostDetailTableViewCell cellWithTableView:tableView];
PostDetailModel *detailModel = self.presenter.detailArray[indexPath.row];
detailCell.detailModel = detailModel;
return detailCell;
}
#pragma mark - PostDetailPresenterDelegate
- (void)presenter:(PostDetailPresenter *)presenter status:(ResponseStatusModel *)statusModel error:(NSError *)error {
if (error) {
//有缓存显示缓存,无缓存显示错误信息
if (self.presenter.detailArray.count > 0) {
[self.listTableView reloadData];
}
} else {
if (statusModel.status == 1) {
[self.listTableView reloadData];
} else {
//显示msg
}
}
}
代码规范
1、多用#pragma mark - XXXXX便于代码区域区分。
@interface TestViewController ()
{
NSInteger _testIndex;
}
@property (nonatomic, strong) UIButton *testButton;
@end
@implementation TestViewController
#pragma mark - life cycle
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
#pragma mark - CustomDelegate
- (void)xxxxxx {
}
#pragma mark - event response
- (void)yyyyyy {
}
#pragma mark - lazy load
- (UIButton *)testButton {
}
2、减少#define的使用,多使用如下方式:
const常量有数据类型,而宏常量没有数据类型。编译器可以对前者进行类型安全检查,而对后者只进行字符替换,没有类型安全检查,并且在字符替换时可能会产生意料不到的错误(边际效应)。StackOverflow链接
//支付宝支付后的通知
extern NSString *const hybAliPayNotification;
//微信支付后的通知
extern NSString *const hybWeChatPayNotification;
//支付宝支付后的通知
NSString *const hybAliPayNotification = @"ReceiveAliPayNotification";
//微信支付后的通知
NSString *const hybWeChatPayNotification = @"ReceiveWeChatPayNotification";
3、@IBOutlet 的 didSet
如果我们由于某种原因,确实需要在代码中设置一些 view 的属性,在连接 @IBOutlet 后,不少开发者会选择在 viewDidLoad 中进行设置。其实个人认为一个更合适的地方是在该 @IBoutlet 的 didSet 中进行。@IBoutlet 所修饰的也是一个属性,这个关键词所做的仅只是将属性暴露给 IB,所以它的各种属性观察方法 (willSet,didSet 等) 也会被正常调用。
@IBOutlet var myTextField: UITextField! {
didSet {
// Workaround for https://openradar.appspot.com/28751703
myTextField.layer.borderWidth = 1.0
myTextField.layer.borderColor = UIColor.lineGreen.cgColor
}
}
4、关于View的布局
1、纯代码或Xib或SB的方式都可以,复杂界面推荐使用纯代码布局。关于SB
2、纯代码方式用Autolayout可以考虑使用Masonry。
5、目录结构
缓存及热更新
缓存
列表页如首页feed流、圈子帖子列表及好孕医院添加缓存,帖子详情暂不缓存。
缓存策略:
1、网络请求之前先加载缓存,若存在缓存,显示缓存数据。网络请求成功后,更新缓存,刷新列表,展示最新请求的数据。若不存在缓存且网络请求失败,展示空页面提示;
2、只缓存首屏数据,如第一次网络请求20条,则缓存20条数据,主要是确保列表不为空;
3、根据缓存的帖子ID来区分已读、未读UI样式;