iOS相关

UITableView reloadData not worki

2018-02-06  本文已影响34人  iOS_Ru

这个bug 找了两天 很蛋疼

dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });

首先发现 上面方法 刷新 tableView 居然有问题

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section这个方法走
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 这个方法不走

控制器VC的 属性tableView

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    return _tableView;
}

1.刚开始发现问题 数据源 modleList 更新了 然后cell没有更新
2.慢慢的发现 tableView的代理方法- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 打印这个的tableView和self.tableView 居然不是一个对象 地址不同
3.后来追踪问题到 不知道哪个小伙控制器的方法老爱重写init方法
控制器的int重写-(instancetype)init { if (self = [super init]) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutAction) name:tokenInvalid object:nil]; } return self; }
在logoutAction 里面居然 调用了[self.tableView reloadData];

这么就是问题的所在了

只要是控制器 在没有走viewDidLoad方法的时候去接收到这个通知就会有问题、终于找到了复现问题的操作了

这里解释 其实是跟控制器的生命周期 self.view的创建等有关
到Init方法里注册了通知 在没有走viewDidLoad方法的时候执行通知的方法时候会在tableView的懒加载里调用 self.view 这里就会调用self 的viewDidLoad方法
会造成 tableView的懒加载走了两次 就会有2个tableView
然后self.tableView持有的对象 和 self addSubView 的tableView不是同一个对象
所有就会造成数据源刷新了 而代理没有走。 因为现在的self.tableView就没有superView父视图 就不走代理方法。

哎呀妈呀 这个Bug 找的真是头疼

奉劝大家 写控制器不要跟自定义view一样 不要轻易去重写Init方法 属性完全可以在viewDidLoad里去初始化啊

上一篇下一篇

猜你喜欢

热点阅读