【发布时间】:2015-06-18 19:37:56
【问题描述】:
在 UITableView 委托方法 cellForRowAtIndexPath:(NSIndexPath *)indexPath 中,我想为一个单元格 imageView 设置图像。如果图像不可用,我想下载它,然后在完整块中异步设置它。问题是因为单元格是可重用的,可能在调用完成块时,单元格可能不再存在。 调用完成块时如何更新单元格?或者这样可以吗?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FriendTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Friend Cell"];
Friend *friend = self.friends[indexPath.row];
if (friend.picture) {
cell.userProfileImageView.image = [UIImage imageWithData:pictureData];
} else {
cell.userProfileImageView.image = nil;
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=normal&return_ssl_res", friend.facebookId]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];
// Run network request asynchronously
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil && data != nil) {
friend.picture = data;
FriendTableViewCell *cellToUpdate = (FriendTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cellToUpdate.userProfileImageView.image = [UIImage imageWithData:data];
}
}];
}
return cell;
}
【问题讨论】:
标签: ios objective-c uitableview