2013-03-07 106 views
3

我将CustomImageView添加到UITableViewCell。UITableView重载数据崩溃

UITableViewCell *cell = nil; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell1"] autorelease]; 
    } 
    CustomImageView *customIV = [[CustomImageView alloc] init]; 
    [cell.contentView addSubView:customIV]; 
    [customIV release]; 

但是,当我尝试重新加载tableview时,发生错误。

错误调用堆栈如下所示。

enter image description here

输出字符串如下。

- [CustomImageView上海华]:发送到释放实例0x1f848f30

+2

试试这个:[cell.contentView addSubview:customIV]; – Vishal 2013-03-07 04:09:39

+2

你可以发布'cellForRowAtIndexPath'的完整代码吗? – 2013-03-07 04:14:08

+0

@ttotto您需要在单元格的内容视图中添加子视图,而不是单元格本身。请参阅下面的iManan答案。 – 2013-03-07 04:19:19

回答

1
CustomImageView *customIV = [[CustomImageView alloc] initWithFrame:CGRectMake(x, y, w, h)]; 
[cell.contentView addSubView:customIV]; 

它与我做的时候我已经发布了内存不足的提示。
所以根据我的说法,不需要释放,因为它会释放内存。

希望它能帮助你。
谢谢。

+1

为什么它的价值,customIV会在这种情况下泄漏。 – 2013-03-07 04:19:58

0

发生此错误是因为您创建的每个时间CustomImageView对象创建时您的cell

所以,最好的办法就是先初始化的CustomImageView对象,然后创建UITableView

诸如此类,

CustomImageView *customIV把它放在你的.h file,然后@synthesize.m File

(把这个代码之上UITableView

self.customIV = [[CustomImageView alloc] init]; 

然后创建UITableView

self.tablView = [[UITableView alloc]init]; 
. 
. 
. 
. 

而且在cellForRowAtIndexPath只添加[cell.contentView addSubView:self.customIV];

+2

如果自定义图像视图需要出现在多行中,则这不起作用。 – rmaddy 2013-03-07 04:38:47

+0

@ rmaddy- ya但每次在单元格 – iPatel 2013-03-07 04:41:02

+1

中使用CustomImageView的实例单个视图不能出现在多个父视图中。因此,如果将'CustomImageView'添加到表中的多行上,则不可能拥有单个实例。 – rmaddy 2013-03-07 04:43:18

1

尝试评论此行[customIV release]; &运行,而重新加载数据应该不会崩溃。

这个背后的原因是每次它试图创建新的自定义视图&释放它,所以导致系统&崩溃发生额外的负载。

+0

你的想法很好,但是当OP释放customIV的obj多于一次时,它会有所帮助..这里的OP只发布一次:) – iPatel 2013-03-07 04:49:27

+0

我知道它释放对象一次,但它会释放对象并且每次都会在乘法中创建对象表格行中的内容。所以我的基本问题是为什么要在每个单元格中添加相同的CustomImageView? – 2013-03-07 04:58:17

1

您只想将图像添加到每个单元格一次。你的代码改成这样:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell1"]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell1"] autorelease]; 
     CustomImageView *customIV = [[CustomImageView alloc] init]; 
     [cell.contentView addSubView:customIV]; 
     [customIV release]; 
    } 

    return cell; 
} 

如果不工作,那么你需要证明你完全cellForRowAtIndexPath方法。通过仅显示部分代码,您很难提供帮助。