没有ARC的UITableViewCell标识符泛滥内存

Pha*_*oan 0 objective-c uitableview ios automatic-ref-counting

我正在开发一个没有ARC的旧项目.它有很多错误,代码看起来很难看,我正在重写它.

快速浏览一下我的代码吧

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    cell = [self createCellWithInfo:[self.search objectAtIndex:indexPath.row]];
    return cell;
}

-(UITableViewCell *)createCellWithInfo:(NSDictionary *)info{

    UITableViewCell * cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@“Cell”] autorelease];
    //set image for cell
    //set text for cell.textlabel
    //set text for cell.detailTextLabel
    //create an UIButton and add to cell.content view
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

重点在于这行代码 [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@“Cell”] autorelease]

如果我@"Cell"在这里使用,那么当我在桌面上不停地上下滚动时,内存会升起.滚动约15秒后,我的iphone 5c变得滞后.

如果我把它设置为nil,一切都很好.

有人可以解释一下吗?我不喜欢非ARC.

谢谢.

Cla*_*fou 5

if块内部,您正在创建单元而不调用自动释放,这会在没有ARC的情况下泄漏内存.

if块之后,无论如何都要重新创建它(无论它是否被回收),这次使用自动释放,您应该做的就是重置其相关​​属性,以便您可以成功重用已回收的单元格(或配置新单元格) ).

尝试更换代码,如下所示:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    [self updateCell:cell withInfo:[self.search objectAtIndex:indexPath.row]];
    return cell;
}

-(void)updateCell:(UITableViewCell *)cell withInfo:(NSDictionary *)info{
    //set image for cell
    //set text for cell.textlabel
    //set text for cell.detailTextLabel
    //create an UIButton and add to cell.content view
}
Run Code Online (Sandbox Code Playgroud)