Reputation: 556
I have a UITableView which displays fetched RSS dynamically, I have now customized the RSS to return the image name so that i can later on add a UIImageView to to every cell in the table which displays the image beside every cell, here is the code for adding the image
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(0, 0, 40, 40);
NSString *path = [NSString stringWithFormat:@"URL/%@",object.imageName]; //"object" is the returned Object from the RSS, so basically what i am doing is appending the image name to the path url.
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
imageView.image = [UIImage imageWithData:data];
[cell addSubview:imageView];
[cell bringSubviewToFront:imageView];
so when i run my app the app runs slowly and even stops for a small amount of time, the reason for that is that i am loading all RSS imaged directly in this line NSData *data = [NSData dataWithContentsOfURL:url];
any solution for this problem ?
Thank you in advance
i actually thought of fetching the images in a separate thread,
dispatch_queue_t fetchImage = dispatch_queue_create("Fetching Image", NULL);
dispatch_async(fetchImage, ^{
NSData *data = [NSData dataWithContentsOfURL:url];
});
dispatch_release(fetchImage);
but doing so wont allow me to use the variable "data" outside the queue. any idea ?
Upvotes: 0
Views: 408
Reputation: 1377
You should retrieve your data asynchronously ! May be the use of a Open Source libraries will help you:
Or you can also use the NSURLConnection
class with the asynchronous mode.
Upvotes: 0
Reputation: 4731
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *path = [NSString stringWithFormat:@"URL/%@",object.imageName];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithData:data];
}); });
Upvotes: 3
Reputation: 14816
The method [NSData dataWithContentsOfURL:]
is synchronous: whenever you call it, it blocks the current thread (which is almost certainly your app's main thread) for as long as it takes to complete. This is very bad. Aside from making the UI feel janky, there's a watchdog process that will kill unresponsive apps.
You really, really want to use asynchronous network calls. Read up on NSURLConnection
, but know, also, that there are many articles and libraries and samples out there on this exact subject: loading images asynchronously for display in a table view. Start with, maybe, AFNetworking's category on UIImageView
, or maybe a library like SDWebImage.
Upvotes: 0