UITableViewCell内存管理

时间:2012-11-20 17:36:10

标签: objective-c ios xcode memory-management

非常基本的cellForRowAtIndexPath实现。

我想知道为什么分析仪告诉我我在这里泄漏了内存。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    MyObject *object = [[self.datasource objectForKey:key] objectAtIndex:indexPath.row];

    cell.textLabel.text = object.title;

    return cell;
}

分析仪告诉我'细胞'可能会泄漏。这只是分析仪中的一个弱点,或者我该如何处理它呢?

注意:像这样添加对自动释放的调用:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier] autorelease];

导致崩溃。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果您不使用ARC,那么您应该自动释放该单元格:

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

请注意,这是不等效,并在从dequeueReusableCellWithIdentifier:检索后自动释放它,因为该方法会针对特定单元格多次调用,而过度自动释放会导致崩溃。< / p>

答案 1 :(得分:0)

您应该将自动释放放在分配新单元格的行上:

 cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
相关问题