uiviewcontroller中的多个tableview

问题描述:

我试过这个,但在cellforrowatindexpath上得到一个异常错误uiviewcontroller中的多个tableview

下面是我得到的异常。在

断言失败 - [UITableView的_createPreparedCellForGlobalRow:withIndexPath:],/SourceCache/UIKit_Sim/UIKit-1914.84

if(aTableView==specTable) 
{ 
    static NSString *CellIdentifier = @"cell"; 
    UITableViewCell *cell = [specTable dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if(cell==nil) 
    { 
     cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 
            reuseIdentifier:CellIdentifier]; 

    } 

    return cell; 

} 
else 
{  
    static NSString *CellIdentifier2 = @"cell2"; 
    UITableViewCell *cell= [table2  dequeueReusableCellWithIdentifier:ReviewCellIdentifier2]; 
} 

return cell; 
+1

至少,请作出努力,以提供一个编译例子......和格式化你的代码!你不能正确使用空格,缩进等。很难读懂你写的东西! – 2012-08-01 07:58:06

+1

您不应该使用'CellIdentifier2'而不是'ReviewCellIdentifier2'吗?另外,返回单元应该在else语句中,它正在丢失范围。 – Joe 2012-08-01 08:00:40

两个问题:

  1. 你永远不返回cell2。在此方法结束时,无论发件人表格视图是否等于第一个或第二个,您总是会返回cell
  2. 如果在第二部分中(else分支)dequeueReusableCellWithIdentifier:消息返回nil,则不像第一部分中那样创建单元。

总而言之:

if (aTableView == specTable) 
{ 
    static NSString *cellIdentifier = @"cell"; 
    UITableViewCell *cell = [specTable dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 
            reuseIdentifier:CellIdentifier] autorelease]; // you were also leaking memory here 

    } 

    return cell; 

} 
else 
{  
    static NSString *cellIdentifier2 = @"cell2"; 
    UITableViewCell *cell2 = [table2 dequeueReusableCellWithIdentifier:cellIdentifier2]; 
    if (cell2 == nil) 
    { 
     cell2 = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 
            reuseIdentifier:CellIdentifier] autorelease]; 

    } 
    return cell2; 
} 

return nil; // just to make the compiler happy 
+0

我可以知道这是什么内存泄漏? – user1302602 2012-08-01 17:19:10

+1

如果您不使用ARC,则必须使用autorelease补偿分配。 – 2012-08-01 17:21:30