относительно UITableView - PullRequest
       6

относительно UITableView

0 голосов
/ 15 марта 2011

Я новичок в программировании iPhone ... У меня есть приложение, похожее на фотогалерею, где я загружаю изображения и заголовки для каждой ячейки в UITableView, используя сервер с JSON.Когда я прокручиваю таблицу, программа вылетает!

-(NSInteger) tableView : (UITableView *) tableView numberOfRowsInSection:(NSInteger) section {
    return [id_arr count];

}

-(CGFloat) tableView : (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {
    return 80;
}

//
// tableView:cellForRowAtIndexPath:
//
// Returns the cell for a given indexPath.
//
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];


    }

    NSString *tmp3=[NSString stringWithFormat:@"%@",[path_arr objectAtIndex:indexPath.row]];
    tmp3=[tmp3 stringByReplacingOccurrencesOfString:@"(" withString:@""];
    tmp3=[tmp3 stringByReplacingOccurrencesOfString:@")" withString:@""];
    tmp3=[tmp3 stringByReplacingOccurrencesOfString:@" " withString:@""];
    tmp3=[tmp3 stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSLog(@"URL:%@",tmp3);


    NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:tmp3]];

    //NSLog(@"Image DATA:%@",[path_arr objectAtIndex:0]);
    UIImage* image1 = [[UIImage alloc] initWithData:imageData];
    UIImageView *imgview=[[UIImageView alloc]initWithImage:image1];
    imgview.frame=CGRectMake(5, 5, 56, 68);
    imgview.backgroundColor=[UIColor redColor];
    [cell.contentView addSubview:imgview];


    UILabel *lbl_desc=[[UILabel alloc]initWithFrame:CGRectMake(70, 1, 240, 50)];
    NSString *tmp=[NSString stringWithFormat:@"%@",[descrip_arr objectAtIndex:indexPath.row]];
    tmp=[tmp stringByReplacingOccurrencesOfString:@"(" withString:@""];
    tmp=[tmp stringByReplacingOccurrencesOfString:@")" withString:@""];
    tmp=[tmp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    //tmp=[tmp stringByReplacingOccurrencesOfString:@" " withString:@""];
    lbl_desc.text=tmp;
    lbl_desc.font=[UIFont systemFontOfSize:14];
    lbl_desc.lineBreakMode=UILineBreakModeWordWrap;
    lbl_desc.numberOfLines=0;
    lbl_desc.textAlignment=UITextAlignmentLeft;
    lbl_desc.backgroundColor=[UIColor clearColor];
    [cell.contentView addSubview:lbl_desc];


    NSLog(@"A_count:%@",[count_arr objectAtIndex:0]);
    UILabel *lbl_page=[[UILabel alloc]initWithFrame:CGRectMake(230, 50, 100, 20)];
    NSString *tmp1=[NSString stringWithFormat:@"%@",[count_arr objectAtIndex:indexPath.row]];
    NSLog(@"A_count1:%@",tmp1);
    tmp1=[tmp1 stringByReplacingOccurrencesOfString:@"(" withString:@""];
    tmp1=[tmp1 stringByReplacingOccurrencesOfString:@")" withString:@""];
    tmp1=[tmp1 stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    tmp1=[tmp1 stringByAppendingString:@"  Images"];
    NSLog(@"A_count123:%@",tmp1);
    lbl_page.text=tmp1;
    lbl_page.font=[UIFont systemFontOfSize:12];
    lbl_page.lineBreakMode=UILineBreakModeWordWrap;
    lbl_page.numberOfLines=0;
    lbl_page.textAlignment=UITextAlignmentLeft;
    lbl_page.backgroundColor=[UIColor clearColor];
    [cell.contentView addSubview:lbl_page];

    cell.backgroundColor=[UIColor clearColor];

    [imageData release];
    [image1 release];
    [imgview release];
}

Ответы [ 3 ]

2 голосов
/ 15 марта 2011

Вы должны return cell; в конце функции.

1 голос
/ 15 марта 2011

ОК, возможно, не ответ сам по себе, но эта строка меня беспокоит:

NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:tmp3]];

вы загружаете данные synchrounousl; y каждый раз, когда появляется новая ячейка, т.е. каждый раз, когда вы прокручиваете таблицу?

И вам не нужно проверять возвращаемое значение этого - что делать, если этот запрос не выполняется - вы получите nil как imagedata и это не может быть хорошо.

Вам нужно загрузить изображениеданные в фоновом потоке, используя NSURLConnection асинхронно , и вам обязательно нужно проверить, что вы получили считанные данные изображений с сервера!

1 голос
/ 15 марта 2011

Вы должны добавить элементы управления ячейки во время инициализации ячейки, а затем настроить значения для каждого из них, используя viewWithTag:

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.backgroundColor=[UIColor clearColor];

        UIImageView *imgview=[[UIImageView alloc] init];
        imgview.frame = CGRectMake(5, 5, 56, 68);
        imgview.backgroundColor=[UIColor redColor];
        imgview.tag = 1;
        [cell.contentView addSubview:imgview];
        [imgview release];

        UILabel *lbl_desc=[[UILabel alloc] initWithFrame:CGRectMake(70, 1, 240, 50)];
        lbl_desc.font=[UIFont systemFontOfSize:14];
        lbl_desc.lineBreakMode = UILineBreakModeWordWrap;
        lbl_desc.numberOfLines = 0;
        lbl_desc.textAlignment = UITextAlignmentLeft;
        lbl_desc.backgroundColor = [UIColor clearColor];
        lbl_desc.tag = 2;
        [cell.contentView addSubview:lbl_desc];
        [lbl_desc release];

        UILabel *lbl_page=[[UILabel alloc] initWithFrame:CGRectMake(230, 50, 100, 20)];
        lbl_page.font=[UIFont systemFontOfSize:12];
        lbl_page.lineBreakMode = UILineBreakModeWordWrap;
        lbl_page.numberOfLines = 0;
        lbl_page.textAlignment = UITextAlignmentLeft;
        lbl_page.backgroundColor = [UIColor clearColor];
        lbl_page.tag = 3
        [cell.contentView addSubview:lbl_page];
        [lbl_page release];
    }

    NSMutableString *tmp3 = [NSString stringWithFormat:@"%@",[path_arr objectAtIndex:indexPath.row]];
    [tmp3 replaceOccurrencesOfString:@"(" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp3 length])];
    [tmp3 replaceOccurrencesOfString:@")" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp3 length])];
    [tmp3 replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp3 length])];
    [tmp3 replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp3 length])];
    NSLog(@"URL:%@",tmp3);    

    UIImageView* imgView = (UIImageView *)[cell viewWithTag:1];
    imgView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tmp3]]];

    NSMutableString *tmp = [NSString stringWithFormat:@"%@",[descrip_arr objectAtIndex:indexPath.row]];
    [tmp replaceOccurrencesOfString:@"(" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp length])];
    [tmp replaceOccurrencesOfString:@")" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp length])];
    [tmp replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp length])];
    [tmp replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp length])];
    UILabel *lblDesc = (UILabel *)[cell viewWithTag:2];
    lblDesc.text = tmp;

    NSLog(@"A_count:%@",[count_arr objectAtIndex:0]);

    NSMutableString *tmp1=[NSString stringWithFormat:@"%@",[count_arr objectAtIndex:indexPath.row]];
    NSLog(@"A_count1:%@",tmp1);
    [tmp1 replaceOccurrencesOfString:@"(" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp1 length])];
    [tmp1 replaceOccurrencesOfString:@")" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp1 length])];
    [tmp1 replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[tmp1 length])];
    [tmp1 appendString:@"  Images"];
    NSLog(@"A_count123:%@",tmp1);
    UILabel *lblPage = (UILabel *)[cell viewWithTag:3];
    lblPage.text = tmp1;

    return cell;
}

. В приведенном выше коде я переместил создание универсального (в таблицу) элемента управления/ setup для инициализации ячейки, чтобы она выполнялась только один раз (поскольку ячейки используются повторно).Затем я ссылаюсь на эти элементы управления, используя пользовательский тег, назначенный каждому из них.Я также добавил правильные операторы release для ваших элементов управления, удалил ненужное распределение UIImage и NSData и изменил ваши строки на изменяемые, чтобы сделать всю эту настройку более простой и производительной.Вы также не смогли вернуть ячейку, поэтому я добавил это в качестве последней строки этого метода.

Я оставил ваш код поиска изображения в такте, но, как указал deanWombourne получение этого здесь - ужасный план, еще более сложный, потому что нет никакой проверки, что данные были получены.Вы захотите реализовать фоновый поток, который загружает эти изображения по одному во временный кеш.Затем в вышеописанном методе вы можете извлекать эти изображения из этого кэша, а не извлекать их каждый раз (см. Этот вопрос для получения дополнительной информации: Кэширование URL-изображений iphone UITableview )

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