Reputation: 1424
I need to know if it's better to use NSOperation or Block to load a large number of image into a UIScrollView? I create all the Imageview and positioning each UIImageView in the right position into the scroll.
To avoid memory warning I choose to load the image once at time. My idea is to create a sort of queue and insert all the image to load in the queue. I have to use block or NSOperation to do this?
Upvotes: 2
Views: 3731
Reputation: 29524
In tableView:cellForRowAtIndexPath:
, you can use GCD (Grand Central Dispatch) to load the images asynchronously.
Like this:
static NSString *CellIdentifier = @"ImageCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
NSString *imagepath = //get path to image here
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
dispatch_sync(dispatch_get_main_queue(), ^{
[[cell imageView] setImage:image];
[cell setNeedsLayout];
});
});
return cell;
Edit: For a better answer, watch WWDC '12 Session 211 - "Building Concurrent User Interfaces on iOS" (thanks @sc0rp10n!)
Upvotes: 5
Reputation: 38475
If you want a queue then NSOperationQueue (and therefore NSOperations) is a sensible thing to use :)
Upvotes: 2