2014-01-24 79 views
2

調整的UIImage我調整了UIImages以下方法內存泄漏而在弧

- (UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)newSize forName:(NSString *)name { 
    UIGraphicsBeginImageContext(newSize); 
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; 
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    [_dictSmallImages setObject:newImage forKey:name]; 
    return newImage; 
} 

而且在的UITableView的cellForRowAtIndexPath方法,我用它像這樣

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    [[cell.contentView viewWithTag:indexPath.row + 1] removeFromSuperview]; 

    // Configure the cell... 
    NSString *imageName = [NSString stringWithFormat:@"img%d", indexPath.row + 1]; 
    CGRect imageRect = CGRectMake(8, 5, 304, 190); 

    UIImage *scaledImage = [_dictSmallImages objectForKey:imageName]; 
    if (![_dictSmallImages objectForKey:imageName]) { 
     scaledImage = [self resizeImage:[UIImage imageNamed:imageName] toSize:CGSizeMake(304, 190) forName:imageName]; 
    } 

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:imageRect]; 
    [imgView setTag:indexPath.row + 1]; 
    [imgView setContentMode:UIViewContentModeScaleAspectFit]; 
    [imgView setImage:scaledImage]; 
    [cell.contentView addSubview:imgView]; 

    if ((lastIndexPath.row == 10 && indexPath.row == 0) || indexPath.row == lastIndexPath.row) { 

     if (_delegate) { 
      NSString *imgName = [NSString stringWithFormat:@"img%d", indexPath.row + 1]; 
      [_delegate selectedText:imgName]; 
     } 

     [imgView.layer setBorderColor:[UIColor yellowColor].CGColor]; 
     [imgView.layer setBorderWidth:5.0f]; 
     [imgView setAlpha:1.0f]; 
     lastIndexPath = indexPath; 
    } 
    return cell; 
} 

但是當我通過配置文件檢查泄漏時,儀器顯示泄漏如 Leak shown in Instruments

任何人都可以請讓我知道爲什麼這個泄漏是?

回答

4

還有,你應該知道關於-imageNamed:,尤其是當你決定與它合作的兩個主要事實:

  1. -imageNamed:返回一個自動釋放的圖像,這將在未來一段時間內自動釋放。
  2. -imageNamed也緩存它返回的圖像。緩存保留圖像。

如果您不釋放它,緩存將繼續保留圖像,直到它釋放它爲止,例如發生內存警告時。因此,當您使用imageNamed獲取圖像時,它不會被釋放,直到緩存被清除。

如果您不希望圖像因任何原因而被緩存,則應使用其他方法創建它們,例如,-imageWithContentsOfFile:不會緩存圖像。

您可以預期從-imageWithContentsOfFile:返回的圖像對象將被自動釋放並且不會被緩存,並且會在運行循環結束時釋放它。

+1

感謝您的解釋,不知道這個! –

+1

感謝您的解釋@Bhavin我在閱讀文檔時應該小心,再次感謝 – channi

+0

@channi:很高興爲您效力! – Bhavin