`

UITableViewDataSource的方法

 
阅读更多

UITableViewDataSource的方法被苹果设计为同步的:

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

我感觉这有点问题,因为在loadView方法里,一旦设置了UITableView的dataSource,上面2个delegate方法就会被调用,而且是在ui thread里调用。但是如果这时候去访问数据库的话,就会阻塞主线程

所以我的做法是在loadView方法最后,在子线程异步访问数据库,然后再次调用reloadData方法

{
    BOOL loadMembersDone;
}

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(!loadMembersDone){
        return nil;
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[UITableViewCell reuseIdentifier]];
    if(!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[UITableViewCell reuseIdentifier]];
    }
    cell.textLabel.text = [[members objectAtIndex:indexPath.row] objectForKey:@"name"];
    return cell;
}

-(void) loadView
{
    ContactView *view = [[ContactView alloc] initWithController:self];
    self.tableView = view;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self loadEnterprises];
        [self loadMembers];
    });
}

-(void) loadMembers
{
   // 从数据库中读取
    
    loadMembersDone = YES;
    [self.tableView reloadData];
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics