【问题标题】:Memory leak in UITableView when scrolled on iOS 5.1在 iOS 5.1 上滚动时 UITableView 中的内存泄漏
【发布时间】:2012-04-29 15:15:09
【问题描述】:

UITableview 每次滚动,都会有 48 个字节的内存泄漏。 负责库:libsystem_c.dylib 负责框架:strdup。

这仅在 iOS 5.1 上观察到,而不在早期版本上观察到。 其他人也面临同样的问题吗?这是 iOS 5.1 中的错误吗?

代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath(NSIndexPath *)indexPath 
{
    NSString *cellIdentifier = [[NSString alloc] initWithString:@"fontSelectionCell"];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    [cellIdentifier release];

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

    cell.textLabel.text = [fontNameList objectAtIndex:[indexPath row]];
    cell.selectionStyle =UITableViewCellSelectionStyleGray;
    cell.textLabel.font = [UIFont systemFontOfSize:17.0];

    if ([fontName isEqualToString:cell.textLabel.text])
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.textLabel.textColor = [UIColor blueColor];

    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.textColor = [UIColor blackColor]; 
    }

    return cell;
}

【问题讨论】:

  • 显示一些代码可能是什么? cellForRowAtIndexPath: 方法会是最有趣的......你也在你的项目中使用 ARC 吗?
  • 您是否使用了没有自定义代码的默认实现?是泄漏,还是稍后会清除内存(因为自动释放的对象)。
  • @jaydee3,我用基本表格视图测试了一个简单的应用程序,但内存泄漏仍然存在。
  • 我也看到了这个问题,在极少数情况下,当一直向上滚动并弹跳然后一直滚动到底部时,它会导致多次泄漏,并在某一时刻用 SIGKILL 杀死了应用程序。

标签: ios uitableview memory-leaks


【解决方案1】:

我认为您遇到的这个问题已经在 iOS 5.1 上报告过了。我自己也有。目前我无法在苹果论坛中找到有关此问题的链接。

【讨论】:

【解决方案2】:

这可能与您处理单元格标识符的方式有关。我真的很惊讶它并没有崩溃,因为你释放了cellIndentifier,但是在创建新单元格时引用它(即当一个单元格没有从dequeueReusableCellWithIdentifier返回重复使用时)。

使用单元标识符的标准/公认方法是使用静态(因为它永远不会改变,并且它只会被分配一次而不是潜在的 100 次,因为cellForRowAtIndexPath 在以下情况下被不断调用滚动表格)。这将使您的代码更有效率。

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *cellIdentifier = @"fontSelectionCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
    }   

   ...
}

您可以尝试更改cellIdentifier 看看是否还有泄漏?

【讨论】:

  • 嗨,我尝试使用静态 NSString 作为 cellIdentifier,但在滚动 tableView 时仍然出现相同的内存泄漏。
  • 你看到哪个类/类型正在泄漏吗?仪器显示什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多