Search code examples
objective-cxcodeuiimageviewuiimageaqgridview

delaying in loading images in the AQGridView in Objective-C


In my app, I have a root view which is a gridview. I am loading an images in the gridview cells.I am having problem with the loading images. As soon as I launch the app, there will be blank cells with out images after a second the images are loading into the cells. Is there any way to solve this issue. The below is my code.

UIImage *defaultImage = [UIImage imageNamed:@"addEmployee.png"];
if (!employee.imageName) {
    return defaultImage;
}

  if ([_imageCache objectForKey:employee.imageName]) {
      return [_imageCache objectForKey:employee.imageName];
  }

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    UIImage *image = [UIImage imageWithContentsOfFile:[self  imagePath:employee.imageName]];
    dispatch_async(dispatch_get_main_queue(), ^ {
        if (image) {
            [_imageCache setObject:image forKey:employee.imageName];
            cell.imageView.image = image;
        } else {
            [_imageCache setObject:defaultImage forKey:employee.imageName];
            cell.imageView.image = defaultImage;
            return;
        }
    });
});

 return cell.imageView.image;

}

Solution

  • Loading images takes time, there is no way to make it instant. Your code seems sensible, you are loading the images off the main thread so it will not block the UI, and caching them once loaded. The only way to make it faster is to load less images or make the images smaller.