iOS MVVM + RAC 简单实例讲解

在MVVM 中,view 和 view controller正式联系在一起,我们把它们视为一个组件
view 和 view controller 都不能直接引用model,而是引用视图模型(viewModel)
viewModel 是一个放置用户输入验证逻辑,视图显示逻辑,发起网络请求和其他代码的地方
view 引用viewModel ,但反过来不行(即不要在viewModel中引入#import UIKit.h,任何视图本身的引用都不应该放在viewModel中)(PS:基本要求,必须满足)
viewModel 引用model,但反过来不行


本文里用MVVM模式,以及RAC双向数据绑定,来讲解“未读消息”的标记这个小栗子(小红点的隐藏与显示)。效果图

iOS MVVM + RAC 简单实例讲解_第1张图片

思路讲解:
viewModel 绑定整个视图,通过viewModel获得列表model后,创建cellModel(cell的viewModel),每个cell绑定cellModel,cell根据cellModel变化而变化
iOS MVVM + RAC 简单实例讲解_第2张图片

结构:
iOS MVVM + RAC 简单实例讲解_第3张图片
image.png

上代码
viewController:viewWillAppear都去获取第一条消息的ID

@interface TJMMineViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) TJMMineHeader *mineHeader;
@property (strong, nonatomic) IBOutlet TJMMineViewModel *viewModel;

@end

@implementation TJMMineViewController
#pragma  mark -  view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configViews];
    [self configTableview];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_viewModel getSignalMessage];//viewWillAppear都去获取第一条消息的ID
}

#pragma  mark - configViews
- (void)configViews {
    [self setTitle:@"我 的" fontSize:18 colorHexValue:0x73d7ff];   
    [self setRightNaviItemWithImageName:@"mine_setting" orTitle:nil titleColorHexValue:0 fontSize:0];
}

- (void)configTableview {
    self.tableView.tableHeaderView = self.mineHeader;
    [_tableView registerNib:[UINib nibWithNibName:@"TJMMineCell" bundle:nil] forCellReuseIdentifier:cMineCell];
}

#pragma  mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJMMineCell *cell = [tableView dequeueReusableCellWithIdentifier:cMineCell forIndexPath:indexPath];
    cell.cellModel = self.viewModel.dataSource[indexPath.row];//绑定cellModel
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.viewModel.rowHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [TJMUnloginView showWithLoginResult:^{
        TJMMineCellModel *cellModel = self.viewModel.dataSource[indexPath.row];
        [self performSegueWithIdentifier:cellModel.segueId sender:nil];
    }];
}

model.h

@interface TJMMineModel : NSObject

@property (nonatomic, copy) NSString *imageName;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *segueId;
@property (nonatomic, assign) BOOL isMessageItem;//如果不是消息那一行则为NO

@end

viewModel.h

@interface TJMMineViewModel : TJMListBaseViewModel

@property (nonatomic, assign) CGFloat rowHeight;
/**获取消息列表的第一条数据,并对比*/
- (void)getSignalMessage;
@end

viewModel.m
1.得到model array 后,用RAC map 方法 将 [model] 转换为包含model的[cellModel]

    NSArray *mapArr = [[array.rac_sequence map:^id _Nullable(id  _Nullable value) {
        TJMMineCellModel *cellModel = [[TJMMineCellModel alloc]init];
        cellModel.model = value;
        return cellModel;
    }] array];

2.获取消息列表的第一条数据,与本地数据对比,如果不一样则表示有新消息,想cellModel的 isExitUnreadMsg 属性 标记为YES,反之标记为NO。(此时cell 已绑定了 cellModel 所以 isExitUnreadMsg 变化 cell 也会跟着变化)

NSString *unreadId = [[NSUserDefaults standardUserDefaults] stringForKey:kUnreadMessageId];

TJMMessageModel *model = [TJMMessageModel mj_objectWithKeyValues:successObj[@"data"]];
            TJMMessageRecordModel *record = model.records.firstObject;
            if (!unreadId) {
                [[NSUserDefaults standardUserDefaults] setObject:record.ID forKey:kUnreadMessageId];
            } else {
                 TJMMineCellModel *msgCellModel = self.dataSource[2];
                if (![unreadId isEqualToString:record.ID]) {
                    msgCellModel.isExitUnreadMsg = YES;
                } else {
                    msgCellModel.isExitUnreadMsg = NO;
                }
            }

完整代码

- (id)init {
    if (self = [super init]) {
        //获取Model
        NSArray *array = [TJMMineModel mj_objectArrayWithFile:[[NSBundle mainBundle] pathForResource:@"TJMMineModel" ofType:@"plist"]];
    NSArray *mapArr = [[array.rac_sequence map:^id _Nullable(id  _Nullable value) {
        TJMMineCellModel *cellModel = [[TJMMineCellModel alloc]init];
        cellModel.model = value;
        return cellModel;
    }] array];
    self.dataSource = [NSMutableArray arrayWithArray:mapArr];
    }
    return self;
}

#pragma  mark - lazy loading

- (CGFloat)rowHeight {
    if (!_rowHeight) {
        self.rowHeight = 70.f * TJMHeightRatio;
    }
    return _rowHeight;
}

- (void)getSignalMessage {
    TJMTokenModel *tokenModel = [TJMSandBoxManager getTokenModel];
    if (tokenModel) {
        NSString *unreadId = [[NSUserDefaults standardUserDefaults] stringForKey:kUnreadMessageId];
        NSDictionary *parameters = @{@"currentPage" : @1,
                                     @"pageSize" : @1,
                                     @"customerId" : tokenModel.userId
                                     };
        [TJMNetworkingManager GET:TJMApiBasicAddress(TJMGetMessage) isNeedToken:YES parameters:parameters progress:nil success:^(id successObj, NSString *msg) {
            TJMMessageModel *model = [TJMMessageModel mj_objectWithKeyValues:successObj[@"data"]];
            TJMMessageRecordModel *record = model.records.firstObject;
            if (!unreadId) {
                [[NSUserDefaults standardUserDefaults] setObject:record.ID forKey:kUnreadMessageId];
            } else {
                 TJMMineCellModel *msgCellModel = self.dataSource[2];
                if (![unreadId isEqualToString:record.ID]) {
                    msgCellModel.isExitUnreadMsg = YES;
                } else {
                    msgCellModel.isExitUnreadMsg = NO;
                }
            }
        } failure:^(NSInteger code, NSString *failString) {
            
        }];
    }
}

cell.h

@interface TJMMineCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet TJMLabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *dotView;
@property (nonatomic, strong) TJMMineCellModel *cellModel;

@end

cell.m
这里只说明消息那个小红点的绑定,
先看combineLatestWith:reduce: 方法,绑定两个信号,判断状态返回一个新的信号;
所以dotView 的隐藏与否,取决于这个signal 是否满足,“reduce”后的判断条件(即这个cell既要是“我的消息”---->isMessageItem == YES,且还要有未读消息isExitUnreadMsg == YES,才会显示小红点)

if (isMessageItem.boolValue) {
            if (isExitUnreadMsg.boolValue) {
                return @0;
            } else {
                return @1;
            }
        } else {
            return @1;
        }

完整代码

- (void)setCellModel:(TJMMineCellModel *)cellModel {
    if ([cellModel isEqual:_cellModel]) return;
    _cellModel = cellModel;
    RAC(_iconImageView, image) = RACObserve(cellModel, image);
    RAC(_titleLabel, text) = RACObserve(cellModel, title);
    RAC(_dotView, hidden) = [RACSignal combineLatest:@[RACObserve(cellModel, isMessageItem), RACObserve(cellModel, isExitUnreadMsg)] reduce:^id (NSNumber *isMessageItem, NSNumber *isExitUnreadMsg){
        if (isMessageItem.boolValue) {
            if (isExitUnreadMsg.boolValue) {
                return @0;
            } else {
                return @1;
            }
        } else {
            return @1;
        }
    }];
}

cellModel.h

@interface TJMMineCellModel : TJMBaseViewModel

@property (nonatomic, strong) TJMMineModel *model;

@property (nonatomic, copy) NSString *imageName;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *segueId;
@property (nonatomic, assign) BOOL isMessageItem;

@property (nonatomic, assign) BOOL isExitUnreadMsg;
@property (nonatomic, strong) UIImage *image;

@end

cellModel.m 就是绑定model

- (void)setModel:(TJMMineModel *)model {
    if ([model isEqual:_model]) return;
    _model = model;
    RAC(self, title) = RACObserve(_model, title);
    RAC(self, isMessageItem) = RACObserve(_model, isMessageItem);
    @weakify(self);
    [RACObserve(_model, imageName) subscribeNext:^(NSString *  _Nullable x) {
        @strongify(self);
        self.image = [UIImage imageNamed:x];
    }];
    RAC(self, segueId) = RACObserve(_model, segueId);
}

你可能感兴趣的:(iOS MVVM + RAC 简单实例讲解)