从UITableViewController中分离出dataSource,更轻量级的UIViewController

有时候我们的控制器会非常庞大,一部分原因就是控制器要获取数据,可能包含从网络中加载数据,这时候我们需要把获取dataSource这部分代码分离出来,创建一个新的类。

1. tableView分离dataSource

分离UITableViewController中的dataSource到一个单独的类,并实现UITableViewDataSource协议及其方法。

ArrayDataSource.h

    typedef void (^TableViewCellConfigureBlock)(id cell, id item);

    @interface ArrayDataSource : NSObject <UITableViewDataSource>

    - (id)initWithItems:(NSArray *)anItems
         cellIdentifier:(NSString *)aCellIdentifier
         configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;

    - (id)itemAtIndexPath:(NSIndexPath *)indexPath;

    @end           

ArrayDataSource.m

    @interface ArrayDataSource ()

    @property (nonatomic, strong) NSArray *items;
    @property (nonatomic, copy) NSString *cellIdentifier;
    @property (nonatomic, copy) TableViewCellConfigureBlock configureCellBlock;

    @end

    @implementation ArrayDataSource

    - (id)init
    {
        return nil;
    }

    - (id)initWithItems:(NSArray *)anItems
         cellIdentifier:(NSString *)aCellIdentifier
         configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock
    {
        self = [super init];
        if (self) {
            self.items = anItems;
            self.cellIdentifier = aCellIdentifier;
            self.configureCellBlock = [aConfigureCellBlock copy];
        }
        return self;
    }

    - (id)itemAtIndexPath:(NSIndexPath *)indexPath
    {
        return self.items[(NSUInteger) indexPath.row];
    }

    #pragma mark UITableViewDataSource

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return self.items.count;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier
                                                        forIndexPath:indexPath];
        id item = [self itemAtIndexPath:indexPath];
        self.configureCellBlock(cell, item);
        return cell;
    }

    @end

使用该dataSource,只需要initWithItems即可,并把该dataSource赋值给tableView.dataSource

    - (void)setupTableView
    {
        TableViewCellConfigureBlock configureCell = ^(PhotoCell *cell, Photo *photo) {
            [cell configureForPhoto:photo];
        };
        NSArray *photos = [AppDelegate sharedDelegate].store.sortedPhotos;
        self.photosArrayDataSource = [[ArrayDataSource alloc] initWithItems:photos
                                                             cellIdentifier:PhotoCellIdentifier
                                                         configureCellBlock:configureCell];
        self.tableView.dataSource = self.photosArrayDataSource;
        [self.tableView registerNib:[PhotoCell nib] forCellReuseIdentifier:PhotoCellIdentifier];
    }

2. 从UIViewController中分离网络请求

单独定义一个UIViewControllerData类,实现网络请求。该类实现UIViewController中定义的协议,在指定时刻去加载数据,进行网络请求,并把获取的数据通过调离的block返回给控制器,控制器在进行其他操作(如tableView reload)

.h

    @interface UIViewControllerData : NSObject <RefreshableListViewControllerDataSource>

    + (instancetype)sharedInstance;

    @end

.m

    @implementation UIViewControllerData

    + (instancetype)sharedInstance {
        static UIViewControllerData *instance;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[UIViewControllerData alloc] init];
        });
        return instance;
    }

    - (void)refreshableListViewController:(RefreshableListViewController *)controller loadDataFrom:(NSUInteger)offset limit:(NSUInteger)limit withUserToken:(NSString *)token         completion:(void (^)(NSArray *, BOOL))completionBlock fail:(void (^)(NSError *))failBlock {
        //网络请求数据
        [UserAPI query:param userToken:token completion:^(NSArray<UserProfileSimplify> *userProfiles, BOOL hasMore) {
                if (completionBlock) {
                    completionBlock(userProfiles,hasMore);
                }
            } error:^(ServerAPIError *error) {
                DDLogDebug(@"---MYLOG:出错啦!---");
            }];
        } error:failBlock];
    }

    @end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,041评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,262评论 4 61
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,977评论 6 342
  • 前几天妹妹跟我聊重庆森林。 看这部电影的时候还是在大学,依稀记得熄灯后,几个男生光着膀子围坐在一个笔记本前,边吃泡...
    抓狂的生蚝阅读 705评论 0 1
  • 沐xin然阅读 132评论 1 2