Question

I am currently loading my table with a left-sided thumbnail, title and subtitle using 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"];

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

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

    return cell;
}

Of course this will not work in production due to the synchronous loading I am doing here.

What is your suggestion for asynchronous loading of images in a situation like this?

I've found AF Networking (haven't used it yet) but wonder if there's a more lightweight approach to this issue.

Was it helpful?

Solution

AsyncImageView is your friend, check it out here.

Just set the imageURL and you are good to go.

OTHER TIPS

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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top