【问题标题】:UITableViewCell memory managementUITableViewCell 内存管理
【发布时间】:2012-11-20 17:36:09
【问题描述】:

非常基本的 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;
}

分析仪告诉我“细胞”可能会泄漏。这只是分析仪的一个弱点还是我应该如何处理?

注意:像这样添加对 autorelease 的调用:

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

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

【问题讨论】:

  • 在你的 if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } 你的 alloc/init 中没有自动释放看看是否有帮助

标签: objective-c ios xcode memory-management


【解决方案1】:

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

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

请注意,这与从 dequeueReusableCellWithIdentifier: 检索后自动释放它不等效,因为该方法会为特定单元格多次调用,并且过度自动释放会导致崩溃。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 2012-03-21
      • 1970-01-01
      • 2011-08-17
      • 2016-10-12
      相关资源
      最近更新 更多