保留iPhone SDK中的计数问题

VsN*_*VsN -1 iphone cocoa memory-management

我对检查对象的保留计数有一点疑问:

请找到下面的代码,它在释放对象内存后显示retainCount为1.

- (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] autorelease];
        CGRect contentRect = [cell.contentView bounds];     
        UIImageView *thumbView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:IMAGE_CELL_BACKGROUND]];
        thumbView.frame = contentRect;      
        cell.backgroundView=thumbView;
        [thumbView release];
    }
    UIImageView *image=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"left_arrow.png"]];
    **NSLog(@"Image retain count %d",[image retainCount]);**
    image.frame=CGRectMake(290, 12.5, [UIImage imageNamed:@"left_arrow.png"].size.width,  [UIImage imageNamed:@"left_arrow.png"].size.height);
    image.backgroundColor=[UIColor clearColor];
    [cell.contentView addSubview:image];
    [image release];
    **NSLog(@"Image retain count-- after %d",[image retainCount]);**


        // Configure the cell...

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

Tam*_*más 6

这是完全正常的.cell.contentView仍然保留对图像的引用.当你调用时[cell.contenetView addSubview:image],cell.contentView将图像引用存储在某个地方(可能是在一个数组或类似的东西中),它会将引用计数器增加1,以确保imagecell.contentView仍然使用它时不会释放它.无论何时cell.contentView因任何原因而解除分配,都将确保图像的保留计数减少1.