UITableView重载数据崩溃
我将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时,发生错误。
错误调用堆栈如下所示。
输出字符串如下。
- [CustomImageView上海华]:发送到释放实例0x1f848f30
CustomImageView *customIV = [[CustomImageView alloc] initWithFrame:CGRectMake(x, y, w, h)];
[cell.contentView addSubView:customIV];
它与我做的时候我已经发布了内存不足的提示。
所以根据我的说法,不需要释放,因为它会释放内存。
希望它能帮助你。
谢谢。
为什么它的价值,customIV会在这种情况下泄漏。 – 2013-03-07 04:19:58
发生此错误是因为您创建的每个时间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];
尝试评论此行[customIV release];
&运行,而重新加载数据应该不会崩溃。
这个背后的原因是每次它试图创建新的自定义视图&释放它,所以导致系统&崩溃发生额外的负载。
你的想法很好,但是当OP释放customIV的obj多于一次时,它会有所帮助..这里的OP只发布一次:) – iPatel 2013-03-07 04:49:27
我知道它释放对象一次,但它会释放对象并且每次都会在乘法中创建对象表格行中的内容。所以我的基本问题是为什么要在每个单元格中添加相同的CustomImageView? – 2013-03-07 04:58:17
您只想将图像添加到每个单元格一次。你的代码改成这样:
- (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
方法。通过仅显示部分代码,您很难提供帮助。
试试这个:[cell.contentView addSubview:customIV]; – Vishal 2013-03-07 04:09:39
你可以发布'cellForRowAtIndexPath'的完整代码吗? – 2013-03-07 04:14:08
@ttotto您需要在单元格的内容视图中添加子视图,而不是单元格本身。请参阅下面的iManan答案。 – 2013-03-07 04:19:19