Search code examples
iosobjective-cuitableviewuiimageviewsdwebimage

SDWebImage and UITableViewCell with multiple UiImageViews doesn't show all images


I need to show multiple images in each UITableViewCell. To do that, I use SDWebImage to asynchronously download the images. I run the following code within a configCell method in my UITableViewCell:

        for (int i=0; i<allOrganizationIds.count; i++) {
            self.orgView = [[UIImageView alloc] initWithFrame:CGRectMake((self.frame.size.width - 10) - (55 * position), 3, 50, 15)];
            org = [[DLOrganizationManager getInstance] organizationForId:[allOrganizationIds[i] intValue]];

            [self.orgView sd_setImageWithURL:[NSURL URLWithString:org.organizationLogoUrl] placeholderImage:[UIImage imageNamed:@"category-selected"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                [self addSubview:self.orgView];
            }];
        }

The problem is that it only shows one image per cell, even when there should be three. Thecomplete block only gets executed once. When scrolling the particular cell out of the view and back, all images are visible.

Why doesn't the UIImageView get updated each time an image has successfully been downloaded, even while the cell is still visible?


Solution

  • You overwrite your orgView property on each loop iteration, meaning that the first view you create gets deallocated shortly after the second iteration because it is not retained by anyone.

    Also, every image view you add have the same frame because the position variable do not change in the scope of the for loop. You should probably make use of your i variable in the frame calculation.

    for (int i=0; i<allOrganizationIds.count; i++) {
        UIImageView *orgView = [[UIImageView alloc] initWithFrame:CGRectMake((self.frame.size.width - 10) - (55 * position), 3, 50, 15)];
        [self addSubview:orgView]; // The image view is then strongly retained by it's superview
        org = [[DLOrganizationManager getInstance] organizationForId:[allOrganizationIds[i] intValue]];
    
        [orgView sd_setImageWithURL:[NSURL URLWithString:org.organizationLogoUrl] placeholderImage:[UIImage imageNamed:@"category-selected"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            // Do wathever you want here
            // If this view is opaque without an image in it you can play with the hidden property to acheive the same effect as if you added it as a subview here
        }];
    }