针对多个细胞优化CellForRow方法

时间:2016-01-07 08:26:31

标签: ios optimization

如果我们在两个单元格中都有相同的内容,比如2个标签和1个imageview,那么任何人都可以帮助我优化下面的代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == booksTbl) { // Your conditions here to choose between Books and Movies
    BookCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bookCell"];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:@"bookCell"];
    }
    return cell;
} else {
    MovieCell *cell = [tableView dequeueReusableCellWithIdentifier:@"movieCell"];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:@"movieCell"];
    }
    return cell;
}

我已经尝试过采用UITablewViewCell作为常见且根据条件,我使用适当的单元格进行投射。但它对我没有用。

1 个答案:

答案 0 :(得分:1)

试试这个:

BookCell *cell = (BookCell*)[tableView dequeueReusableCellWithIdentifier:@"bookCell"];


if(cell == nil){
    // NSLog(@"---Cell Allocated Memory---");
    cell = (BookCell *)[[[NSBundle mainBundle] loadNibNamed:@"BookCell" owner:nil options:nil] lastObject];
    [cell setRestorationIdentifier:@"bookCell"];
}