问题有两部分:(1)明确,如何维护异步操作结果的顺序,(2)使用cell暗示,如何正确处理异步请求以支持tableview。
第一个问题的答案比较简单:保持请求的结果与请求的参数相关联。
// change avatars to hold dictionaries associating PFFiles with images
@property(nonatomic,strong) NSMutableArray *avatars;
// initialize it like this
for (PFFile *imageFile in self.imageFiles) {
[avatars addObject:[@{@"pfFile":imageFile} mutableCopy]];
}
// now lets factor an avatar fetch into its own method
- (void)avatarForIndexPath:(NSIndexPath *)indexPath completion:^(UIImage *, NSError *)completion {
// if we fetched already, just return it via the completion block
UIImage *existingImage = self.avatars[indexPath.row][@"image"];
if (existingImage) return completion(existingImage, nil);
PFFile *pfFile = self.avatars[indexPath.row][@"pfFile"];
[pfFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
UIImage *avatar = [UIImage imageWithData:imageData];
self.avatars[indexPath.row][@"image"] = avatar;
completion(avatar, nil);
} else {
completion(nil, error);
}
}];
}
好的,第 (1) 部分。对于第 2 部分,您的 cellForRowAtIndexPath 代码必须识别单元格被重用。当异步图像提取发生时,您正在处理的单元格可能已经滚动了。通过不引用完成块中的单元格(仅indexPath)来解决此问题。
// somewhere in cellForRowAtIndexPath
// we're ready to setup the cell's image view
UIImage *existingImage = self.avatars[indexPath.row][@"image"];
if (existingImage) {
cell.userImageView.image = existingImage;
} else {
cell.userImageView.image = // you can put a placeholder image here while we do the fetch
[self avatarForIndexPath:indexPath completion:^(UIImage *image, NSError *error) {
// here's the trick that is often missed, don't refer to the cell, instead:
if (!error) {
[tableView reloadRowsAtIndexPaths:@[indexPath]];
}
}];
}
重新加载完成块中的行将导致再次调用cellForRowAtIndexPath,除非在随后的调用中,我们将拥有一个现有的图像并且单元格将立即得到配置。