2013-03-12 4 views
0

Я отображая 100 удаленных изображений в tableviewВнимание памяти, когда клетки воссозданы в Tableview

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 


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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) { 

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 

} 

cell.imageView.image = nil; 
cell.textLabel.text = nil; 
cell.detailTextLabel.text = nil; 
cell.selectionStyle = UITableViewCellSelectionStyleNone; 


// Configure the cell... 

for (UIView *view in cell.contentView.subviews) { 
    if ([view isKindOfClass:[UIButton class]] || [view isKindOfClass:[UILabel class]]||[view isKindOfClass:[UIImageView class]]) { 
     [view removeFromSuperview]; 
    } 
} 

int imageNumber = 0; 

if (isInSearchMode) 
{ 
    PhotoVO *photoVO = (PhotoVO *)[searchResultArray objectAtIndex:indexPath.row]; 

    UIImageView *photo_View = [[UIImageView alloc]initWithFrame:CGRectMake(20, 5, width , height - 10)]; 
    photo_View.tag = 101; 
    [[photo_View layer] setBorderWidth:3.0f]; 
    [[photo_View layer] setBorderColor:[UIColor whiteColor].CGColor]; 
    [photo_View setImageWithURL:[NSURL URLWithString:photoVO.thumb_URL1] placeholderImage:[UIImage imageNamed:@"loader"]]; 


    [cell.contentView addSubview:photo_View]; 

    UILabel *stringLable=[[UILabel alloc]initWithFrame:CGRectMake(130, 20, 150, 30)]; 
    stringLable.backgroundColor=[UIColor clearColor]; 
    stringLable.text=photoVO.photoName; 
    stringLable.font=[UIFont systemFontOfSize:16.0]; 
    [cell.contentView addSubview:stringLable]; 

    UILabel *tagLable=[[UILabel alloc]initWithFrame:CGRectMake(130, 55, 150, 30)]; 
    tagLable.backgroundColor=[UIColor clearColor]; 
    tagLable.text=photoVO.tagString; 
    tagLable.font=[UIFont systemFontOfSize:12.0]; 

    [cell.contentView addSubview:tagLable]; 


} 
else 
{ 

    for (int i = (indexPath.row * imagesCount); i < ((indexPath.row *imagesCount) + imagesCount); i++) { 

     if (i < [cellImageVOArray count]) { // If resultsArray Count is odd then we no need to create cell image 

      PhotoVO *photoVo = (PhotoVO *)[cellImageVOArray objectAtIndex:i]; 

      UIButton *appIconBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 

      appIconBtn.frame = CGRectMake(((imageNumber * 5)+5)+(imageNumber * width), 2, width, height -4); 

      appIconBtn.tag = i + 100; 
      [[appIconBtn layer] setBorderWidth:3.0f]; 
      [[appIconBtn layer] setBorderColor:[UIColor whiteColor].CGColor]; 

      [appIconBtn addTarget:self action:@selector(imageTapped:) forControlEvents:UIControlEventTouchUpInside]; 

      [appIconBtn setBackgroundImageWithURL:[NSURL URLWithString:photoVo.thumb_URL1] placeholderImage:[UIImage imageNamed:@"loader.png"]]; 

      //[appIconBtn setBackgroundImageWithURL:[NSURL URLWithString:photoVo.thumb_URL1]]; 

      [cell.contentView addSubview:appIconBtn]; 
      imageNumber ++; 

     } 

    } 



} 

return cell; 

} 

Я использую приведенный выше код для отображения изображений в tableView, но я получаю предупреждение памяти во всех отношениях я проверяю Это. Я думаю, что ячейка создается каждый раз, поэтому, пожалуйста, скажите мне, видите ли какие-либо проблемы в коде.

ответ

5

Это проблема: NSString *CellIdentifier = [NSString stringWithFormat:@"%d",indexPath.row];

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

Второй, Вы должны думать о том, что вы делаете здесь:

for (UIView *view in cell.contentView.subviews) { 
    if ([view isKindOfClass:[UIButton class]] || [view isKindOfClass:[UILabel class]]||[view isKindOfClass:[UIImageView class]]) { 
     [view removeFromSuperview]; 
    } 
} 

Everytime клетка нужна вы удаляете те части, которые делают клетку, а затем переделывают их сразу после. Вы должны использовать его как можно больше в UITableView. Вы должны задуматься о создании пользовательского подкласса UITableViewCell, в котором есть нужные вам фрагменты, а затем используйте это. Сказано, что похоже, что у вас есть только изображение и две метки, которые были бы установлены по умолчанию UITableViewCell, поэтому вам, вероятно, не придется создавать их вообще, если ваша ячейка не является обычным явлением.

Наконец, вы должны посмотреть, что вы делаете с isInSearchMode. Сейчас у вас в основном есть оператор if для всей таблицы. Это не ужасная вещь, но если вы это сделаете, у вас должны быть два идентификатора ячейки, по одному для каждой возможной ячейки. Затем в операторе if просто меняйте идентификаторы ячеек и заполняйте соответствующие данные.

Прежде всего, если это вообще возможно (что, кажется, в вашем случае), вы не должны создавать новые виды в этом методе. Вы должны разрешить дескриптор UITableViewCell.

Создание пользовательских ячеек

Вы можете начать с простого подкласса UITableViewCell. Затем вы можете добавить свойство для каждой настраиваемой части, которая вам нужна, например, UILabel или UIImageView. И вы можете либо создать их, переопределив init, либо вы можете поместить их в настраиваемое свойство getter, которое создает их по требованию.

// CustomCell.h 
#import <UIKit/UIKit.h> 

@interface Custom : UITableViewCell 

@property (strong, nonatomic) UILabel *titleLabel; 

@end 

// CustomCell.m 
#import "CustomCell.h" 

@implementation CustomCell 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(12.0, 10.0, self.contentView.frame.size.width - 24.0, 22.0)]; 
     [self.titleLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth]; 
     [self.titleLabel setHighlightedTextColor:[UIColor whiteColor]]; 
     [self.titleLabel setFont:[UIFont boldSystemFontOfSize:17.0]]; 
     [self.titleLabel setBackgroundColor:[UIColor clearColor]]; 
     [self.titleLabel setTextColor:[UIColor blackColor]]; 
     [self.titleLabel setAdjustsFontSizeToFitWidth:YES]; 
     [self.titleLabel setMinimumFontSize:8.0]; 

     [self.contentView addSubview:self.titleLabel]; 
    } 
    return self; 
} 

@end 

Тогда вам просто нужно переписать cellForRowAtIndexPath: использовать пользовательский класс. И в вашем случае у вас может быть две пользовательские ячейки и переключаться между ними. Это создаст только достаточное количество каждой ячейки по требованию и повторно использует их при перемещении и выключении экрана.

static NSString *CellIdentifier = @"Cell"; 
static NSString *SearchCellIdentifier = @"SearchCell"; 

if (isInSearchMode) { 
    SearchCell *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:SearchCellIdentifier]; 

    if (cell == nil) { 
     cell = [[SearchCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    cell.titleLabel = @"Custom Search Title"; 

} else { 
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    cell.titleLabel = @"Custom Title"; 

} 

Это может быть легко реорганизовано еще дальше в зависимости от того, как работает ваше приложение, но это должно привести вас к правильному пути.

+0

для (UIView * зрения в cell.contentView.subviews) { если ([вид isKindOfClass: [UIButton класс]] || [смотреть isKindOfClass : [UILabel class]] || [view isKindOfClass: [UIImageView class]]) { [просмотреть removeFromSuperview]; } } Я использую это сначала, я хочу отображать только изображения в формате сетки, когда я нажимаю кнопку поиска, которую я хочу отобразить в другом формате для этой цели. Я удаляю существующие виды. – user2160953

+0

Привет, пожалуйста, расскажите, как создать пользовательскую кнопку в пользовательской ячейке. В каждой ячейке у меня три кнопки – user2160953

+0

Добавлен брифинг. –

0

Да, у вас разные идентификаторы ячеек для каждой строки, поэтому повторного использования не происходит.

Изменение:

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

в

NSString *CellIdentifier = @"CellId"; 
+0

Я написал как этот статический NSString * CellIdentifier = @ "Cell"; – user2160953

Смежные вопросы