Кто может помочь мне найти выделения памяти и утечки?

#iphone #uitableview #memory-leaks #memory-management

#iPhone #uitableview #утечки памяти #управление памятью

Вопрос:

Кто может помочь мне найти выделения памяти и утечки?

 // Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{       
    NSInteger rowIndex = [indexPath row];//row index    
    static NSString *NineCellIdentifier = @"NineCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NineCellIdentifier];   
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:NineCellIdentifier] autorelease];
    }

NSNumber* aHeight = [heightArray objectAtIndex:rowIndex];
itemHeight = [aHeight integerValue];

NSInteger index = 0;
for (int j=0; j< columnNum; j  ) 
{
    CGFloat x, y, w, h;
    x = 0;
    y = 0;
    w = itemWidth;
    h = itemHeight;

    index = rowIndex*columnNum   j;
    if (index >= [itemList count]) 
    {
        break;
    }
    //NSLog(@"index = %d, j= %d", index, j);
    curItem = [itemList objectAtIndex:index];
    NSString *imageFile = [appDelegate.clientResourcesDir stringByAppendingPathComponent:curItem.pic];
    UIImage *image = [UIImage imageWithContentsOfFile:imageFile];
    NSInteger imageWidth = image.size.width;
    NSInteger imageHeight = image.size.height;
    if (imageWidth > itemWidth) 
    {
        imageHeight = imageHeight*itemWidth/imageWidth;
        imageWidth = itemWidth;
    }       

    UIButton *itemBtn = [[UIButton alloc] initWithFrame:CGRectMake(x, y, w, h)];
    [itemBtn setBackgroundColor:[UIColor clearColor]];
    [itemBtn setTag:index];
    [itemBtn addTarget:self action:@selector(goNextPageView:) forControlEvents:UIControlEventTouchUpInside];

    if ([curItem.text1 isEqualToString:@""])
    {
        x = itemBtn.frame.origin.x   (itemWidth - imageWidth)/2;
        y = itemBtn.frame.origin.y   (itemHeight - imageHeight)/2;
    }
    else
    {
        x = itemBtn.frame.origin.x   (itemWidth - imageWidth)/2;
        y = itemBtn.frame.origin.y   (itemHeight - imageHeight - textSize - blankSize)/2;
    }       

    //1 button
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, imageWidth, imageHeight)];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [button setTag:index];
    [button addTarget:self action:@selector(goNextPageView:) forControlEvents:UIControlEventTouchUpInside];
    [itemBtn addSubview:button];
    [button release];

    //2 label
    x = 0;
    y = y   imageHeight   blankSize; 
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, itemWidth, textSize)];
    label.font = [UIFont boldSystemFontOfSize:textSize];
    [label setTextAlignment:UITextAlignmentCenter];
    [label setBackgroundColor:[UIColor clearColor]];        
    label.textColor = [UIColor colorWithRed:rf green:gf blue:bf alpha:1];
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.text = curItem.text1;
    label.tag = -1;     
    [itemBtn addSubview:label];
    [label release];

    //itemBtn.contentMode = UIViewContentModeBottom;
    CGRect frame = itemBtn.frame;
    frame.origin.x = j * itemWidth;
    frame.origin.y = 0;
    itemBtn.frame = frame;

    [cell addSubview:itemBtn];      
    [itemBtn release];
}
return cell;
}
  

Ответ №1:

  1. curItem должен быть выпущен, если у него есть свойство сохранять

Кроме этого, я не вижу никаких утечек в этом фрагменте кода. Утечка может быть где-то в другом месте.

Ответ №2:

Возможно, я что-то упускаю, но я не вижу там ничего, что технически можно было бы считать утечкой. Единственная проблема, которую я вижу, заключается в том, что вы добавляете все свои кнопки каждый раз, когда рисуется ячейка, поэтому в итоге у вас будет много меток и кнопок, и может закончиться память. Вы можете исправить это, каждый раз удаляя все вложенные просмотры. При выполнении этого вы можете захотеть добавить свои кнопки в cell.contentView, а не просто в ячейку, иначе вы можете в конечном итоге удалить представления, которые вы не хотели.

Ответ №3:

itemBtn протекает. Чтобы выяснить, почему это происходит, вы должны понимать, как работает UITableView. Когда он удаляет ячейку из очереди из невидимых на данный момент ячеек, он добавляет itemBtn, даже если он уже был добавлен.

Вы должны создать подкласс UITableViewCell и добавить к нему itemBtn в метод init. В TableView:cellForRowAtIndexPath: вы должны установить только некоторые свойства и не добавлять никаких вложенных представлений в свою ячейку.