2

我目前正在使用以下代码加载带有左侧缩略图、标题和副标题的表格:

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

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

    NSDictionary *post           = [posts objectAtIndex:indexPath.row];

    cell.textLabel.text       = [post objectForKey:@"post_text"];
    cell.detailTextLabel.text = [post objectForKey:@"post_author_name"];

    NSString *postpictureUrl = [post objectForKey:@"picture"];
    NSData   *data           = [NSData dataWithContentsOfURL:[NSURL URLWithString:postpictureUrl]];

    cell.imageView.image = [UIImage imageWithData:data];

    return cell;
}

当然,由于我在这里进行同步加载,这在生产中不起作用。

在这种情况下,您对异步加载图像有什么建议?

我找到了AF Networking(还没有使用它),但想知道是否有更轻量级的方法来解决这个问题。

4

2 回答 2

2

AsyncImageView是你的朋友,看看这里

只需设置imageURL,您就可以开始了。

于 2012-09-29T16:20:51.743 回答
1
Use lazy loading in table view
Use this code


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

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil) {

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

        NSDictionary *post = [posts objectAtIndex:indexPath.row];

        cell.textLabel.text = [post objectForKey:@"post_text"];
        cell.detailTextLabel.text = [post objectForKey:@"post_author_name"];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,  0ul);
        dispatch_async(queue, ^{
         //This is what you will load lazily
      NSString *postpictureUrl = [post objectForKey:@"picture"];
        NSData   *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:postpictureUrl]];
            dispatch_sync(dispatch_get_main_queue(), ^{

        cell.imageView.image = [UIImage imageWithData:data];
                [cell setNeedsLayout];
      }); 
}); 

        return cell;
    }
于 2012-09-29T16:57:16.377 回答