Fetching Twitter Avatars on Separate iOS Thread
I have the following code to populate the UITableView with the tweets.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *uniqueIdentifier = @"UITableViewCell";
UITableViewCell *cell = nil;
if(!isNewSearch) {
cell = [self.tweetsTable dequeueReusableCellWithIdentifier:uniqueIdentifier];
}开发者_如何学Python
Tweet *tweet = [self.tweets objectAtIndex:[indexPath row]];
if(!cell)
{
isNewSearch = NO;
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:uniqueIdentifier] autorelease];
[[cell textLabel] setTextColor:[UIColor whiteColor]];
[[cell textLabel] setNumberOfLines:0];
[[cell textLabel] setLineBreakMode:UILineBreakModeWordWrap];
[[cell textLabel] setFont:[UIFont fontWithName:@"Futura-Medium" size:10]];
// set custom properties
}
[[cell textLabel] setText:[tweet text]];
[[cell imageView] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tweet.profileImageUrl]]]];
return cell;
}
The above code takes an awful lot of time since it is fetching the avatars. Is there anyway I can use blocks and load the avatars on a separate thread and make the interface faster.
You need to look into making that call Asynchronous with NSURLConnection
and it's delegate methods because currently that UIImage call is done in the Main Thread so your UI won't respond until the Image is Downloaded
If you do not want to dive in to NSURLConnection
There is a fantastic Library which does something similar like what you trying to do with Images and Cells. It also provides some sample code which you can use and plug right in: HJCache: iPhone cache library for asynchronous image loading and caching.
Do not use dataWithContentsOfURL:
with remote URLs.
One way to do it is use NSURLConnection
(but not sendSynchronousRequest:returningResponse:error:
) to download the file asynchronously, and then fill in the image when the download is complete. There are also a number of third-party libraries such as ASIHTTPRequest that may be easier to use.
精彩评论