RAC+MVVM

作者: 07212a79db66 | 来源:发表于2016-07-14 17:56 被阅读112次

    MVVM:使用MVVM模式将网络请求以及数据处理放到VM中,主要减轻控制器的负担,使用RAC中的RACCommand发送网络请求.

    M:模型

    #import <Foundation/Foundation.h>
    
    @interface Books : NSObject
    
    @property (nonatomic, strong) NSString *subtitle;
    @property (nonatomic, strong) NSString *title;
    @property (nonatomic, strong) NSString *image;
    
    + (instancetype)bookWithDict:(NSDictionary *)dict;
    @end
    
    
    #import "Books.h"
    
    @implementation Books
    + (instancetype)bookWithDict:(NSDictionary *)dict
    {
        Books *book = [[Books alloc] init];
        
        book.title = dict[@"title"];
        book.image = dict[@"image"];
        book.subtitle = dict[@"subtitle"];
        return book;
    }
    
    @end
    

    V:视图+控制器

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.delegate = self.requestModel;
        tableView.dataSource = self.requestModel;
        [self.view addSubview:tableView];
        self.requestModel.tableView = tableView;
        
        //执行请求
        [self.requestModel.requestCMD execute:nil];
        
    }
    
    

    VM:视图模型

    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import "ReactiveCocoa.h"
    
    @interface RequestViewModel : NSObject<UITableViewDataSource,UITableViewDelegate>
    
    @property (nonatomic, weak) UITableView *tableView;
    /** 请求命令*/
    @property (nonatomic, strong) RACCommand *requestCMD;
    //模型数组
    @property (nonatomic, strong, readonly) NSArray *models;
    
    @end
    
    #import "RequestViewModel.h"
    #import "AFNetworking.h"
    #import "Books.h"
    
    @implementation RequestViewModel
    
    - (instancetype)init {
        if (self == [super init]) {
            [self initialBind];
        }
        return self;
    }
    
    - (void)initialBind {
        _requestCMD = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
                [sessionMgr GET:@"https://api.douban.com/v2/book/search" parameters:@{@"q":@"美女"} progress:^(NSProgress * _Nonnull downloadProgress) {
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
                    //把数据用信号传递出去
                    [subscriber sendNext:responseObject];
                    [subscriber sendCompleted];
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
                return nil;
            }];
    
            //再返回数据信号的时候,把数据中的字典映射成模型信号,传递出去
            return [signal map:^id(NSDictionary *value) {
                NSMutableArray *dicArray = value[@"books"];
                
                NSArray *model = [[dicArray.rac_sequence map:^id(NSDictionary *value) {
                    return [Books bookWithDict:value];
                }] array];
                return model;
            }] ;
        }];
    
        //获取请求的数据
        [_requestCMD.executionSignals.switchToLatest subscribeNext:^(id x) {
            
            //赋值新数据
            _models = x;
            [self.tableView reloadData];
        }];
        
    }
    
    #pragma mark - UITableViewDelegate
    
    #pragma mark - Table view data source
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        return 60;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return self.models.count;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        }
        
        Books *book = self.models[indexPath.row];
        cell.textLabel.text = book.title;
        cell.detailTextLabel.text = book.subtitle;
        
        return cell;
    }
    @end
    

    运行


    相关文章

      网友评论

      • J_WQ:源码地址?
        07212a79db66:@J_WQ 你是说写成这样不会走代理?
        - (void)viewDidLoad {
        [super viewDidLoad];
        RequestViewModel *requestModel = [[RequestViewModel alloc] init];

        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        // tableView.delegate = self.requestModel;
        // tableView.dataSource = self.requestModel;
        // [self.view addSubview:tableView];
        // self.requestModel.tableView = tableView;
        // //执行请求
        // [self.requestModel.requestCMD execute:nil];

        tableView.delegate = requestModel;
        tableView.dataSource = requestModel;
        [self.view addSubview:tableView];
        requestModel.tableView = tableView;
        [requestModel.requestCMD execute:nil];

        requestModel.click = ^(Books *book) {
        NSLog(@"%@",book.title);
        };
        }
        J_WQ:@jianai1 RequestViewModel 作为属性或者全局变量的时候是没有问题的,但是作为局部变量时tableview代理方法不会执行
        07212a79db66:@J_WQ https://github.com/zhaodajun/ReactiveCocoaPra

      本文标题:RAC+MVVM

      本文链接:https://www.haomeiwen.com/subject/pgnejttx.html