iOS開發(fā) MVVM+RAC 的使用

寫在前面
弄了下個人站...防止內(nèi)容再次被鎖定...所有東西都在這里面
welcome~
個人博客

好長一段時(shí)間沒有敲簡書了!
主要是因?yàn)橐恢痹谂苊嬖嚒?br> 終于還是在上海入職了!
由于項(xiàng)目原因最終還是入了MVVM+RAC的坑

下面是正題。

Demo效果

使用MVVM+RAC請求網(wǎng)絡(luò)數(shù)據(jù)


demo.gif

ReactiveCocoa簡介

在iOS開發(fā)過程中,當(dāng)某些事件響應(yīng)的時(shí)候,需要處理某些業(yè)務(wù)邏輯,這些事件都用不同的方式來處理。
比如按鈕的點(diǎn)擊使用action,ScrollView滾動使用delegate,屬性值改變使用KVO等系統(tǒng)提供的方式。
其實(shí)這些事件,都可以通過RAC處理
ReactiveCocoa為事件提供了很多處理方法,而且利用RAC處理事件很方便,可以把要處理的事情,和監(jiān)聽的事情的代碼放在一起,這樣非常方便我們管理,就不需要跳到對應(yīng)的方法里。非常符合我們開發(fā)中高聚合,低耦合的思想。

基礎(chǔ)的話我還是推薦這篇博文 講的都挺細(xì)的
當(dāng)然不爽的話可以試試這個視頻版的,也是某培訓(xùn)機(jī)構(gòu)流出的

Demo分析

本文使用的是豆瓣API(非官方)
Demo所要做的功能很簡單: 從網(wǎng)絡(luò)中請求數(shù)據(jù),并加載到UI上。
MVVM中最重要也就是這個VM了,VM通常與RAC緊密結(jié)合在一起,主要用于事務(wù)數(shù)據(jù)的處理和信號間的傳遞。

Demo中主要使用了下面這些第三方庫

  pod 'SDWebImage'
  pod 'Motis'
  pod 'ReactiveCocoa', '2.5'
  pod 'BlocksKit'
  pod 'AFNetworking'
  pod 'Masonry'
  pod 'SVProgressHUD'

這里除了RAC 還有一個值得提一下

BlocksKit
眾所周知Block已被廣泛用于iOS編程。它們通常被用作可并發(fā)執(zhí)行的邏輯單元的封裝,或者作為事件觸發(fā)的回調(diào)。Block比傳統(tǒng)回調(diào)函數(shù)有2點(diǎn)優(yōu)勢:

  • 允許在調(diào)用點(diǎn)上下文書寫執(zhí)行邏輯,不用分離函數(shù)
  • Block可以使用local variables.

基于以上種種優(yōu)點(diǎn)Cocoa Touch越發(fā)支持Block式編程,這點(diǎn)從UIView的各種動畫效果可用Block實(shí)現(xiàn)就可以看出。而BlocksKit是對Cocoa Touch Block編程更進(jìn)一步的支持,它簡化了Block編程,發(fā)揮Block的相關(guān)優(yōu)勢,讓更多UIKit類支持Block式編程。

代碼

由于BlocksKit的使用,當(dāng)我們寫Delegate和Datasource時(shí) 就不用分離函數(shù),整個邏輯都能湊在一起,比如這樣定義一個collectionView:


- (void)initStyle {
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
    collectionView.backgroundColor = [UIColor redColor];
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:collectionView];
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuide);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    self.collectionView = collectionView;
    
    //注冊cell
    [self.collectionView registerClass:[MovieCollectionViewCell class] forCellWithReuseIdentifier:[MovieCollectionViewCell cellReuseIdentifier]];
    
    //collectionView dataSouce
    A2DynamicDelegate *dataSouce = self.collectionView.bk_dynamicDataSource;
    
    //item個數(shù)
    [dataSouce implementMethod:@selector(collectionView:numberOfItemsInSection:) withBlock:^NSInteger(UICollectionView *collectionView, NSInteger section) {
        return self.listArray.count;
    }];
    //item配置
    [dataSouce implementMethod:@selector(collectionView:cellForItemAtIndexPath:) withBlock:^UICollectionViewCell*(UICollectionView *collectionView,NSIndexPath *indexPath) {
        id<MovieModelProtocol> cell = nil;
        Class cellClass = [MovieCollectionViewCell class];
        if (cellClass) {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:[MovieCollectionViewCell cellReuseIdentifier] forIndexPath:indexPath];
            if ([cell respondsToSelector:@selector(renderWithModel:)]) {
                [cell renderWithModel:self.listArray[indexPath.row]];
            }
        }
        return (UICollectionViewCell *)cell;
    }];
    self.collectionView.dataSource = (id)dataSouce;
    
#define scaledCellValue(value) ( floorf(CGRectGetWidth(collectionView.frame) / 375 * (value)) )

    //collectionView delegate
    A2DynamicDelegate *delegate = self.collectionView.bk_dynamicDelegate;
    
    //item Size
    [delegate implementMethod:@selector(collectionView:layout:sizeForItemAtIndexPath:) withBlock:^CGSize(UICollectionView *collectionView,UICollectionViewLayout *layout,NSIndexPath *indexPath) {
        return CGSizeMake(scaledCellValue(100), scaledCellValue(120));
    }];
    
    //內(nèi)邊距
    [delegate implementMethod:@selector(collectionView:layout:insetForSectionAtIndex:) withBlock:^UIEdgeInsets(UICollectionView *collectionView ,UICollectionViewLayout *layout, NSInteger section) {
        return UIEdgeInsetsMake(0, 15, 0, 15);
    }];

    self.collectionView.delegate = (id)delegate;
    
}

這就將所有有關(guān)collectionView的內(nèi)容都包含在一起了,這樣更符合邏輯。

我們讓viewModel來處理網(wǎng)絡(luò)請求,controller需要做的就是啟動這個開關(guān),并接受數(shù)據(jù)而已,所有的工作交給viewModel來處理

MovieViewModel.m

- (void)initViewModel {
    @weakify(self);
    self.command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            [self getDoubanList:^(NSArray<MovieModel *> *array) {
                [subscriber sendNext:array];
                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }];

}



/**
 網(wǎng)絡(luò)請求

 @param succeedBlock 成功回調(diào)
 */
- (void)getDoubanList:(void(^)(NSArray<MovieModel*> *array))succeedBlock {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableArray *array = [NSMutableArray array];
        MoviewModelList *base = [[MoviewModelList alloc] init];
        [base mts_setValuesForKeysWithDictionary:responseObject];
        
        //遍歷數(shù)組取出 存入數(shù)組并回調(diào)出去
        [base.subjects enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MovieModel *model = [[MovieModel alloc] init];
            [model mts_setValuesForKeysWithDictionary:obj];
            [array addObject:model];
        }];
        if (succeedBlock) {
            succeedBlock(array);
        }
    } failure:nil];
    
}

ViewController.m

- (void)bindViewModel {
    @weakify(self);
    //將命令執(zhí)行后的數(shù)據(jù)交給controller
    [self.viewModel.command.executionSignals.switchToLatest subscribeNext:^(NSArray<MovieModel *> *array) {
        @strongify(self);
        [SVProgressHUD showSuccessWithStatus:@"加載成功"];
        self.listArray = array;
        [self.collectionView reloadData];
        [SVProgressHUD dismissWithDelay:1.5];
    }];
    
    //執(zhí)行command
    [self.viewModel.command execute:nil];
    [SVProgressHUD showWithStatus:@"加載中..."];
}

Demo地址

GitHub

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容