Reputation: 214
I have a data model that includes a property that is an array of UIImages and also a property that is an array of imageURLs (representing the same images).
Upon loading up a certain view, I populate a scrollview with images from the URLS using SDWebImage, which looks nice.
for (NSURL *url in self.project.imageURLs) {
UIImageView *imageView = [[UIImageView alloc]init];
[imageView setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"loading"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[self.scrollview addSubview:imageView];
...some other frame calculations...
}
My question is, how could I, at the same time, load these UIIamges into my data model (self.project.images) without locking up the UI. I'm assuming it's some kind of dispatch_async, but I can't figure out where to call this.
I have both properties because some of the images are coming from a web source and some from the local device/camera.
One possible solution is, when i am asynchronously loading up the data model initially with the urls, to go ahead and load up the UIImages at that time, but it seems like that is using a big chunk of memory that might not be needed. Since I am loading up to 20 projects, all with arrays of images.
Upvotes: 1
Views: 115
Reputation: 1818
In swift 4.2: use this way
DispatchQueue.main.async {
// loading data, adding to an array, setting an image to UIImageView
}
Memory managing version:
DispatchQueue.main.async {[weak weakSelf = self] in
// loading data, adding to an array, setting an image to UIImageView
// use weakSelf to avoid a memory leak: weakSelf.project.images ...
// best way is to create a method in your ViewController – self.updateImage(), and call in this dispatch
}
objC version:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
// use weakSelf here to avoid memory leaking like this:
// [weakSelf updateImageView: indexOfImage];
});
Upvotes: 1