在单独的iOS线程上获取Twitter头像



我有下面的代码来填充UITableView与推文。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

NSString *uniqueIdentifier = @"UITableViewCell";
UITableViewCell *cell = nil;
if(!isNewSearch) {
 cell = [self.tweetsTable dequeueReusableCellWithIdentifier:uniqueIdentifier];
}
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;

}

上面的代码花费了大量的时间,因为它正在获取头像。无论如何,我可以使用块和加载一个单独的线程上的头像,使界面更快。

你需要考虑用NSURLConnection和它的委托方法进行异步调用因为目前UIImage调用是在主线程中完成的所以你的UI在图像下载之前不会响应

如果你不想潜入NSURLConnection有一个梦幻般的库,它做的事情类似于你试图做的图像和细胞。它还提供了一些示例代码,您可以直接使用和插入:HJCache:用于异步图像加载和缓存的iPhone缓存库

禁止使用dataWithContentsOfURL:连接远程url。

一种方法是使用NSURLConnection(而不是sendSynchronousRequest:returningResponse:error:)异步下载文件,然后在下载完成时填充图像。还有一些第三方库,如ASIHTTPRequest,可能更容易使用。

最新更新