繁体   English   中英

Memory 在 UITableView 中将图像加载到自定义单元格时发生泄漏

[英]Memory leak when loading image to custom cell in UITableView

在我的 iPhone 应用程序中,有一个带有自定义单元格的 UITableView。 其中包含 UILabels 和 UIImageViews。 但是当我将图像分配给图像视图时,我得到了 memory 泄漏。 这是代码。 泄漏在方法 cellForRowAtIndexPath 中:我已经提到了泄漏百分比。 请检查代码,这里出了什么问题? 请帮忙。

        //  UIMenuItemCell.h
            @class UIMenuitemImage;
            @interface UIMenuItemCell : UITableViewCell{
                UILabel *cellItemName;
                UIImageView *cellitemImage;
            }
            @property (nonatomic, retain) UILabel *cellItemName;
            @property (nonatomic, retain) UIImageView *cellitemImage;

        //  UIMenuItemCell.m

        #import "UIMenuItemCell.h"

        @implementation UIMenuItemCell
        @synthesize cellItemName, cellitemImage, cellItemButton, cellItemProgress;

        - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
        {
            self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
            if (self) {
                // Initialization code
        //        cellitemImage = [[UIMenuitemImage alloc]init];
            }
            return self;
        }

        - (void)setSelected:(BOOL)selected animated:(BOOL)animated  
        {
            [super setSelected:selected animated:animated];

            // Configure the view for the selected state
        }

    //  MenuScreenVC.m
    - (UIMenuItemCell *) getCellContentView:(NSString *)cellIdentifier {

    CGRect CellFrame = CGRectMake(0, 0, 150, 60);
    CGRect Label1Frame = CGRectMake(20, 23, 98, 30);
    CGRect imgFrame = CGRectMake(20, 48, 110, 123);
    CGRect btnFrame = CGRectMake(25, 136, 100, 30);
    CGRect progressFrame = CGRectMake(25, 140, 100, 21);

    UILabel *lblTemp;
    UIImageView *itemImg;
    UIButton *itemBtn;
    UIProgressView *itemProgView;

    UIMenuItemCell *cell = [[[UIMenuItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
    cell.frame = CellFrame;

    //Initialize Label with tag 1.  
    lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
    lblTemp.tag = 1;
    lblTemp.textColor=[UIColor colorWithRed:139.0f/255.0f green:69.0f/255.0f blue:19.0f/255.0f alpha:1.0f];
    lblTemp.textAlignment = UITextAlignmentCenter;
    lblTemp.backgroundColor = [UIColor clearColor];
    lblTemp.font = [UIFont systemFontOfSize:13.0];
    [cell.contentView addSubview:lblTemp];
    [lblTemp release];

    //Initialize ImageView
    itemImg = [[UIImageView alloc]initWithFrame:imgFrame];
    itemImg.tag = 2;
    [cell.contentView addSubview:itemImg];
    [itemImg release];

    //Initialize Button
    itemBtn = [[UIButton alloc]initWithFrame:btnFrame];
    itemBtn.frame = btnFrame;
    itemBtn.tag = 3;
    itemBtn.titleLabel.textColor = [UIColor blueColor];
    itemBtn.titleLabel.font = [UIFont systemFontOfSize:9.0];
    [cell.contentView addSubview:itemBtn];
    [itemBtn release];

    //Initialize ProgressView
    itemProgView = [[CustomProgressView alloc]initWithFrame:progressFrame];
    itemProgView.tag = 4;
    //[cell.contentView addSubview:itemProgView];
    [itemProgView release];

    return cell;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d", indexPath.row];

    UIMenuItemCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil){
        cell = [self getCellContentView:CellIdentifier];

        cell.transform = CGAffineTransformMakeRotation(M_PI_2);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        cell.cellItemName = (UILabel *)[cell viewWithTag:1];
        cell.cellitemImage = (UIImageView *)[cell viewWithTag:2];
        cell.cellItemButton = (UIButton *)[cell viewWithTag:3];
        cell.cellItemProgress = (UIProgressView *)[cell viewWithTag:4];

        DataBaseClass *itemObj = [appDelegate.itemArray objectAtIndex:indexPath.row];

        __autoreleasing NSString *imageLocalFilePath = nil;
        if ([[tempitemStatusArray objectAtIndex:indexPath.row] isEqualToString:@"NotAvailable"]) {
            cell.cellItemProgress.hidden = YES;
            cell.cellItemButton.hidden = NO;
            imageLocalFilePath = [NSString stringWithFormat:@"%@",[tempItemLocalNotAvailPath objectAtIndex:indexPath.row]];
            NSString *date = [self changeDateFormat:itemObj.itemReleaseDate];          
            [cell.cellItemButton setTitle:date forState:UIControlStateNormal]; 
            cell.cellItemButton.userInteractionEnabled = NO;
            cell.userInteractionEnabled = NO;
            [cell.cellItemButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
            [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"not_available_bttn_bck_img"] forState:UIControlStateNormal];
        }else if ([[tempitemStatusArray objectAtIndex:indexPath.row] isEqualToString:@"Available"]){
            cell.cellItemButton.userInteractionEnabled = YES;
            cell.userInteractionEnabled = YES;
            cell.cellItemProgress.hidden = YES;
            [cell.cellItemButton setTitle:@"" forState:UIControlStateNormal];
            [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"available_bttn_img_normal"] forState:UIControlStateNormal];
            [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"available_bttn_img_pressed"] forState:UIControlStateHighlighted];
            [cell.cellItemButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
            [cell.cellItemButton addTarget:self action:@selector(confirmationAlert:) forControlEvents:UIControlEventTouchUpInside];
            imageLocalFilePath = [NSString stringWithFormat:@"%@",[tempItemLocalAvailPath objectAtIndex:indexPath.row]];
        }else if ([[tempitemStatusArray objectAtIndex:indexPath.row] isEqualToString:@"Active"]) {
            cell.cellItemButton.userInteractionEnabled = YES;
            cell.userInteractionEnabled = YES;
            cell.cellItemProgress.hidden = YES;
            [cell.cellItemButton setTitle:@"" forState:UIControlStateNormal];
            [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"active_bttn_img_normal"] forState:UIControlStateNormal];
            [cell.cellItemButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
            [cell.cellItemButton addTarget:self action:@selector(alert) forControlEvents:UIControlEventTouchUpInside];
            imageLocalFilePath = [NSString stringWithFormat:@"%@",[tempItemLocalAvailPath objectAtIndex:indexPath.row]];
        }else if([[tempitemStatusArray objectAtIndex:indexPath.row] isEqualToString:@"Downloading"]) {
            imageLocalFilePath = [NSString stringWithFormat:@"%@",[tempItemLocalAvailPath objectAtIndex:indexPath.row]];
            [cell.contentView addSubview:myprogressView];
            cell.cellItemButton.hidden = YES;
        }
        if ([imageLocalFilePath isEqualToString:@""]) {
            [cell.cellitemImage setImage:[UIImage imageNamed:@"item01.png"]];
        }else {
            [cell.cellitemImage setImage:[UIImage imageWithContentsOfFile:imageLocalFilePath]];
        }        
        cell.cellItemName.text = [NSString stringWithFormat:@"%@",[tempItemNameArray objectAtIndex:indexPath.row]]; 

        for (UIProgressView *prog in cell.contentView.subviews) {
            if ([prog isKindOfClass:[UIProgressView class]]){
                if (prog.progress == 1) {
                    [prog removeFromSuperview];
                    cell.cellItemButton.hidden = NO;
                    DataBaseClass *itemObj = [appDelegate.itemArray objectAtIndex:indexPath.row];
                    NSString *imageLocalFilePath = nil;
                    if ([[tempitemStatusArray objectAtIndex:indexPath.row] isEqualToString:@"Available"]){
                        cell.cellItemButton.userInteractionEnabled = YES;
                        cell.userInteractionEnabled = YES;
                        cell.cellItemProgress.hidden = YES;
                        [cell.cellItemButton setTitle:@"" forState:UIControlStateNormal];
                        [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"available_bttn_img_normal"] forState:UIControlStateNormal];
                        [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"available_bttn_img_pressed"] forState:UIControlStateHighlighted];
                        [cell.cellItemButton addTarget:self action:@selector(confirmationAlert:) forControlEvents:UIControlEventTouchUpInside];
                    }else if ([[tempitemStatusArray objectAtIndex:indexPath.row] isEqualToString:@"Active"]) {
                        cell.cellItemButton.userInteractionEnabled = YES;
                        cell.userInteractionEnabled = YES;
                        cell.cellItemProgress.hidden = YES;
                        [cell.cellItemButton setTitle:@"" forState:UIControlStateNormal];
                        [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"active_bttn_img_normal"] forState:UIControlStateNormal];
                        [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"active_bttn_img_normal"] forState:UIControlStateHighlighted];
                        [cell.cellItemButton addTarget:self action:@selector(alert) forControlEvents:UIControlEventTouchUpInside];
                    }

                    imageLocalFilePath = [NSString stringWithFormat:@"%@",itemObj.availableLocalIconPath];
                    if ([imageLocalFilePath isEqualToString:@""]) {
                        [cell.cellitemImage setImage:[UIImage imageNamed:@"item01.png"]];
                    }else {
                        [cell.cellitemImage setImage:[UIImage imageWithContentsOfFile:imageLocalFilePath]];
                    }
                    cell.cellItemName.text = [NSString stringWithFormat:@"%@",[tempItemNameArray objectAtIndex:indexPath.row]];

                    [cell.contentView reloadInputViews];
                }
            }
        }

    }else {
        for (UIProgressView *prog in cell.contentView.subviews) {
            if ([prog isKindOfClass:[UIProgressView class]]){
                if (prog.progress == 1) {
                    [prog removeFromSuperview];
                    cell.cellItemButton.hidden = NO;
                    cell.cellItemButton.userInteractionEnabled = YES;
                    cell.userInteractionEnabled = YES;
                    [cell.cellItemButton setTitle:@"" forState:UIControlStateNormal];
                    [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"active_bttn_img_normal"] forState:UIControlStateNormal];
                    [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"active_bttn_img_normal"] forState:UIControlStateHighlighted];
                    [cell.cellItemButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
                    [cell.cellItemButton addTarget:self action:@selector(alert) forControlEvents:UIControlEventTouchUpInside];
                }
            }
        }        
    }

    return cell;
}

用你的方法

- (UIMenuItemCell *) getCellContentView:(NSString *)cellIdentifier

采用:

UIMenuItemCell *cell = [[[UIMenuItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];

编辑以回应评论:

释放iVars的正确方法是使用dealloc方法。 如果没有被调用,则意味着您的UIMenuItemCells没有被释放。 这可能是由于您的实现工作的方式所致。 您正在为表格视图中的每一行创建一个可重复使用的单元格。 我认为,如果将单元格标记为可重复使用,则只有在释放表视图后才能释放该单元格。

您可以通过查看释放表视图时是否释放了所有内存(如果这在您的应用程序中发生)来进行测试。 这意味着您实际上没有泄漏,只是您的应用程序使用了大量内存(很可能是不必要的)。 您还可以测试一下,当将已经创建的行滚动回到屏幕上时,内存是否增加了,因为在这种情况下,我认为您将重复使用单元格,因此内存不应增加。 您也可以尝试使用nil作为单元格标识符来初始化表格视图单元格,以便在滚动到屏幕之外时释放它们。

不过,您可能应该尝试重新编写代码,以便实际上可以重用单元格。 否则,滚动很有可能会非常不稳定。

我遇到类似的问题,终于解决了。

因为您的表格单元格稍后会被重用,

因此只需在将子视图添加到单元格之前调用removeFromSuperview。

我在将图像加载到 imageView 时遇到了 memory 峰值问题。下面的代码解决了我的问题,

注意:这会降低图像质量。 在我的例子中,我在较小的图像视图中加载图像。

        let resizedImage = image.aspectFittedToHeight(100)
        resizedImage.jpegData(compressionQuality: 0.2)
        return resizedImage
    }

并添加此扩展

extension UIImage {
    
    func aspectFittedToHeight(_ newHeight: CGFloat) -> UIImage {
        let scale = newHeight / self.size.height
        let newWidth = self.size.width * scale
        let newSize = CGSize(width: newWidth, height: newHeight)
        let renderer = UIGraphicsImageRenderer(size: newSize)
        return renderer.image { _ in
            self.draw(in: CGRect(origin: .zero, size: newSize))
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM