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

2021-07-17  本文已影响0人  林大鹏

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

DEMO详见

一. 问题场景如下:

// 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还没有值返回,所以会重新进入懒加载方法

具体我们可以看下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

上一篇 下一篇

猜你喜欢

热点阅读