UITableView с проблемами производительности - PullRequest
0 голосов
/ 18 октября 2011

Я делаю UITableview (с IB) в своем приложении с 3 типами ячеек.Все работает отлично, за исключением того, что когда я перетаскиваю свой просмотр таблицы, все становится очень медленным.Так что если кто-то может помочь мне улучшить производительность моего приложения, это будет круто.

Мой код для просмотра таблицы:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[myData objectForKey:@"listnews"] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 154;
    }
    if (indexPath.row == 1) {
        return 34;
    }
    else return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [myTextField resignFirstResponder];

    ListNewsCell *cCell = (ListNewsCell *)[myTable dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"cCellIdentifier%d",indexPath.row]];

    cCell = [[ListNewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"cCellIdentifier%d",indexPath.row]];

    if (indexPath.row == 0) {
        NSString * caroline = [[[myData objectForKey:@"listnews"] objectAtIndex:indexPath.row] objectForKey:@"urlimage"];
        cCell.c1Image1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",caroline]]]];

        cCell.c1Image2.image = [UIImage imageNamed:@"barreNoireHub.png"];

        NSString * sophie = [[[myData objectForKey:@"listnews"] objectAtIndex:indexPath.row] objectForKey:@"titre"];
        NSString *itemTitle = sophie ? [sophie stringByConvertingHTMLToPlainText] : @"[No Title]";
        cCell.c1Label1.text = itemTitle;

        NSString * sonia = [[[myData objectForKey:@"listnews"] objectAtIndex:indexPath.row] objectForKey:@"extrait"];
        NSString *itemExtrait = sonia ? [sonia stringByConvertingHTMLToPlainText] : @"[No Title]";
        cCell.c1Label2.text = itemExtrait;
        }

    if (indexPath.row == 1) {        
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 34)];
        imageView.backgroundColor = [UIColor whiteColor];
        imageView.image = [UIImage imageNamed:@"barreSearchHub.png"];
        [cCell addSubview:imageView];
        [imageView release];

        UIView * insertView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 34)];
        myTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 6, 270, 25)];
        myTextField.placeholder = @"Recherche";
        myTextField.tag = 1;
        myTextField.delegate = self;
        myTextField.returnKeyType = UIReturnKeySearch;

        [insertView addSubview:myTextField];
        cCell.accessoryView = insertView;
    }

    if (indexPath.row > 1) {
        cCell.c2Image1.image = [UIImage imageNamed:@"cellM.png"];

        NSString * caroline = [[[myData objectForKey:@"listnews"] objectAtIndex:indexPath.row] objectForKey:@"urlimage"];
        cCell.c2Image2.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",caroline]]]];

        NSString * sophie = [[[myData objectForKey:@"listnews"] objectAtIndex:indexPath.row] objectForKey:@"titre"];
        NSString *itemTitle = sophie ? [sophie stringByConvertingHTMLToPlainText] : @"[No Title]";
        cCell.c2Label1.text = itemTitle;

        NSString * sonia = [[[myData objectForKey:@"listnews"] objectAtIndex:indexPath.row] objectForKey:@"extrait"];
        NSString *itemExtrait = sonia ? [sonia stringByConvertingHTMLToPlainText] : @"[No Title]";
        cCell.c2Label2.text = itemExtrait;
    }
    return cCell;
}

Код UITableViewCell:

#import "ListNewsCell.h"

@implementation ListNewsCell

@synthesize c1Image1, c1Image2, c1Label1, c1Label2;
@synthesize c2Image1, c2Image2, c2Label1, c2Label2;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        c1Image1 = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,154)];
        c1Image1.backgroundColor = [UIColor clearColor];
        [self addSubview:c1Image1];
        [c1Image1 release];

        c1Image2 = [[UIImageView alloc] initWithFrame:CGRectMake(0,98,320,56)];
        c1Image2.backgroundColor = [UIColor clearColor];
        [self addSubview:c1Image2];
        [c1Image2 release];

        c1Label1 = [[UILabel alloc] initWithFrame:CGRectMake(5, 100, 310, 20)];
        c1Label1.font = [UIFont fontWithName:@"Arial-BoldMT" size:14];
        c1Label1.textColor = [UIColor whiteColor];
        c1Label1.backgroundColor = [UIColor clearColor];
        [self addSubview:c1Label1];

        c1Label2 = [[UILabel alloc] initWithFrame:CGRectMake(5, 112, 310, 45)];
        c1Label2.font = [UIFont fontWithName:@"Arial" size:12];
        c1Label2.textColor = [UIColor whiteColor];
        c1Label2.numberOfLines = 2;
        c1Label2.backgroundColor = [UIColor clearColor];
        [self addSubview:c1Label2];

        c2Image1 = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,70)];
        c2Image1.backgroundColor = [UIColor clearColor];
        [self addSubview:c2Image1];
        [c2Image1 release];

        c2Label1 = [[UILabel alloc] initWithFrame:CGRectMake(105, 8, 180, 20)];
        c2Label1.font = [UIFont fontWithName:@"Arial-BoldMT" size:14];
        c2Label1.textColor = [UIColor blackColor];
        c2Label1.backgroundColor = [UIColor clearColor];
        [self addSubview:c2Label1];

        c2Label2 = [[UILabel alloc] initWithFrame:CGRectMake(105, 25, 180, 45)];
        c2Label2.font = [UIFont fontWithName:@"Arial" size:12];
        c2Label2.textColor = [UIColor blackColor];
        c2Label2.numberOfLines = 2;
        c2Label2.backgroundColor = [UIColor clearColor];
        [self addSubview:c2Label2];

        c2Image2 = [[UIImageView alloc] initWithFrame:CGRectMake(20,10,75,55)];
        c2Image2.backgroundColor = [UIColor clearColor];
        [self addSubview:c2Image2];
        [c2Image2 release];
    }
    return self;
}

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

- (void)dealloc
{
    [super dealloc];
}

@end

Спасибо всем!

Ответы [ 3 ]

2 голосов
/ 18 октября 2011

Следующая строка вызывает большую задержку:

cCell.c2Image2.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",caroline]]]];

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

Загрузите изображение один раз, сделайте его переменной класса, а затем просто повторно используйте его указатель, как:

cCell.c2Image2.image = preloadedImage;

Объявите в своем .h файле:

UIImage * preloadedImage;

А в - (пустом) loadView -метод положить:

preloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",caroline]]]];

Также учтите, что, как писал jrturton, вы хотите повторно использовать свои устаревшие ячейки для дополнительного повышения производительности.

1 голос
/ 18 октября 2011

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

Таким образом, вы можете обернуть все после dequeueReusableCellWithIdentifier внутри if (cCell == nil) (оператор return явно исключен).

0 голосов
/ 18 октября 2011

В методе cellForRowAtIndexPath вы удалили некоторые ячейки из табличного представления. Но вы никогда не использовали это значение. Это вызывало проблему загрузки каждый раз, а не повторного использования.

Попробуйте следующий код, в котором я немного изменил ..

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

{

[myTextField resignFirstResponder];

ListNewsCell *cCell = (ListNewsCell *)[myTable dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"cCellIdentifier%d",indexPath.row]];

if (cCell == nil)

{

cCell = [[ListNewsCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: [NSString stringWithFormat: @ "cCellIdentifier% d", indexPath.row]];

}

if (indexPath.row == 0) {
   // Some code here
    }

if (indexPath.row == 1) {        
    //Some code here
}

if (indexPath.row > 1) {
  // some code here
}
return cCell;

} * * тысяча двадцать-один

Спасибо, Арун.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...