2010-02-03 58 views
-1

为什么我不能将子视图添加到表视图单元格的内容视图?表视图编程

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellTableIdentifier = @"CellTableIdentifier "; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellTableIdentifier]; 
    if (cell == nil) 
    { 
     cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellTableIdentifier]; 
     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 70, 15)]; 
     [email protected]"Name:"; 
     [cell.contentView addSubview:label]; 
    } 
    return [cell autorelease]; 

} 
+4

因为有问题。 (提供详细信息,如果你想要好的答案。) – kennytm 2010-02-03 12:49:55

+0

你当然可以!如果你在使用它的时候遇到了一些问题,那么在你看到它的时候真的不可能帮你。 – Vladimir 2010-02-03 12:50:40

+1

好吧,他不能更新与更多的信息,如果你们关闭它:) – willcodejavaforfood 2010-02-03 12:53:44

回答

3

这应该是一个内存管理的问题。

此声明:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellTableIdentifier]; 

按照Cocoa memory management rule,这不是一个alloc/new/copy方法,也就是说,你没有自己的cell,所以你应该它完成后不-release使用它。然而,接下来的语句(假定cell != nil):

return [cell autorelease]; 

将使cell被释放(一段时间后),引起细胞的双重释放(一段时间后)。因此,您应该只需return cell;

现在如果cell == nil?里面的if分支,你写

cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellTableIdentifier]; 

由于cellalloc创建的,你有责任-release它。但是既然你要把它归还给其他人,你必须放弃所有权,同时避免它不能立即释放。这是使用-autorelease临时将所有权转移到“自动释放池”,以便其他代码可以有机会在它被刷新为无效之前重新获得所有权(-retain)。

换句话说,你应该用cell = [[[...] autorelease];来代替这个声明。

同样,你应该-releaselabel,因为它是-alloc -ed,你不再拥有它。但是,您不需要-autorelease,因为您确定已有其他所有者(cell.contentView)。

总之,你应该重写代码:

static NSString *CellTableIdentifier = @"CellTableIdentifier "; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellTableIdentifier]; 
if (cell == nil) 
{ 
    cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellTableIdentifier] autorelease]; 
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 70, 15)]; 
    [email protected]"Name:"; 
    [cell.contentView addSubview:label]; 
    [label release]; 
} 
return cell; 

顺便说一句,你可以使用UITableViewCellStyleValue2(如地址簿),以避免与视图层次结构搞乱。