美文网首页
UITableView懒加载 调用两次引发的问题

UITableView懒加载 调用两次引发的问题

作者: 林大鹏 | 来源:发表于2021-07-17 12:44 被阅读0次

今天遇到一个问题,就是通过懒加载创建tableView也有可能会创建两次,然后导致一些问题。

DEMO详见

一. 问题场景如下:

  • 就是一个直播间主页,有聊天/主播/在线观众/排行榜等子页面,然后从关注主播列表进入要定位到主播标签下,这时候直播间详情数据加载回来会更新调用直播间加入聊天室逻辑,然后会更新tableView

  • 这时候tableView的懒加载方式如下

// tableView
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 34.f;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = false;
        }
    }
    return _tableView;
}

因为聊天室页面没有调用viewDidLoad,这时候由于调用self.view.bounds,self.view会调用viewControllerview的懒加载,然后会调用viewDidLoad方法,而viewDidLoad里面会调用self.tableView设置相关位置,这时候因为_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];这时候_tableView还没有值返回,所以会重新进入懒加载方法

  • 这时候因为self.view已经有值了,会创建UITableView并返回
  • 这里我们可以看到_tableView的懒加载方法执行了两次。

具体我们可以看下demo打印出来的tableView的值:

2021-01-02 16:51:49.805371+0800 FJFBlogDemo[18398:769654] -----------tableView:<UITableView: 0x7fbe9f83a000; frame = (0 0; 390 844); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x60000312d440>; layer = <CALayer: 0x600003fc85a0>; contentOffset: {0, 0}; contentSize: {0, 0}; adjustedContentInset: {0, 0, 0, 0}; dataSource: (null)>
2021-01-02 16:51:49.805912+0800 FJFBlogDemo[18398:769654] -----------tableView:<UITableView: 0x7fbe9f839400; frame = (0 0; 390 844); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x60000312e070>; layer = <CALayer: 0x600003fc8da0>; contentOffset: {0, 0}; contentSize: {0, 0}; adjustedContentInset: {0, 0, 0, 0}; dataSource: (null)>

两者地址都不一样。

二. 解决方法

修改初始化方法

_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];

尽量不要在懒加载中调用self.view

相关文章

网友评论

      本文标题:UITableView懒加载 调用两次引发的问题

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