Reputation: 40735
Is it safe to load UIImageView
objects in the background, and when done, insert them in the view hierarchy on main thread?
For example you create a GCD block which loads 10 image views in background. At the end you have async block which adds all the UIImageViews
to view hierarchy.
I heard if you create a UIImage
and add it to a UIImageView
then the image data gets loaded on demand when the UIImageView
needs it. How would I force that the UIImage
data gets pulled in the background so it doesnt block main thread for long loading time?
Upvotes: 0
Views: 120
Reputation: 14477
It is always better that if you are downloading images from server you download them on separate thread so It don't block your UI. Once image download complete you can set to that to a specific image view from main thread.
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSData *imageData= [NSData dataWithContentsOfURL:Image_URL];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
__strong __typeof__(weakSelf) strongSelf = weakSelf;
strongSelf.someImageView.image = image;
;
});
});
NOTE:
If you are using AFNetworking
, you can use UIImageView
category and it will handel loading image in background and also can cache it, so If you want to download again it will bring that image from cache.
Upvotes: 1