IOS efficient paging load implementation example

Time:2021-4-30

Today, when reviewing the code, we found that the previous paging loading logic of tableview and collectview had room for optimization, so we optimized it.

1、 Code comparison of tabview’s pagination loading

The code before optimization is as follows:


    [strongSelf.tableView.mj_footer endRefreshing];
    [strongSelf.articleArr addObjectsFromArray:feedList];
    [strongSelf.tableView reloadData];

The optimized code is as follows:


    NSMutableArray *indexPaths = [NSMutableArray array];
    [feedList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
      
      NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(strongSelf.articleArr.count + idx) inSection:0];
      [indexPaths addObject:indexPath];
    }];
    
    [strongSelf.tableView.mj_footer endRefreshing];
    
    [strongSelf.articleArr addObjectsFromArray:feedList];
    
    [strongSelf.tableView beginUpdates];
    [strongSelf.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    [strongSelf.tableView endUpdates];

2、 Code comparison of paged loading in collectonview

The code before optimization is as follows:


     [strongSelf.feedList addObjectsFromArray:feedList];
    if (feedList.count < kPageSize) {
      
      [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
    }else{
      
      [strongSelf.collectionView.mj_footer resetNoMoreData];
    }
    [strongSelf.collectionView reloadData];

The optimized code is as follows:


    NSMutableArray *indexPaths = [NSMutableArray array];
    [feedList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
      
      [indexPaths addObject:[NSIndexPath indexPathForItem:(strongSelf.feedList.count + idx) inSection:0]];
    }];
    
    [strongSelf.feedList addObjectsFromArray:feedList];
    if (feedList.count < kPageSize) {
      
      [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
    }else{
      
      [strongSelf.collectionView.mj_footer resetNoMoreData];
    }
    [strongSelf.collectionView insertItemsAtIndexPaths:indexPaths];

Conclusion: in comparison, after optimization, it seems that the amount of code increases a little, but in theory, the performance of paging loading is better. Previously, the global refresh was used for paging loading, and then the local refresh was used after optimization. So the performance is improved.

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.