今天在review代碼的時候發現之前的tableview 和 collectview 的分頁加載邏輯還有優化的余地,于是進行了優化。
一、tableview的分頁加載的代碼對比
沒有優化之前的代碼如下:
[strongSelf.tableView.mj_footer endRefreshing]; [strongSelf.articleArr addObjectsFromArray:feedList]; [strongSelf.tableView reloadData];
優化之后的代碼如下:
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];
二、collectonview的分頁加載的代碼對比
沒有優化之前的代碼如下:
[strongSelf.feedList addObjectsFromArray:feedList]; if (feedList.count < kPageSize) { [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData]; }else{ [strongSelf.collectionView.mj_footer resetNoMoreData]; } [strongSelf.collectionView reloadData];
優化之后的代碼如下:
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];
總結:相比較之下,優化之后看似代碼量增加了少許,但是從理論上分頁加載的性能更好了。之前分頁加載使用的全局刷新,優化之后改用了局部刷新。從而性能得到提升。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答