ios - 解析PFFile下载顺序iOS
<p><p>我将 5 个 PFFiles 存储在一个数组中,并使用 <code>getDataInBackgroundWithBlock</code> 从 Parse 下载这些文件。</p>
<p>问题是它们在表格 View 单元格中出现的顺序每次都不同,大概是由于文件大小不同,文件下载速度不同。</p>
<pre><code>for (PFFile *imageFile in self.imageFiles) {
[imageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
UIImage *avatar = ;
;
cell.userImageView.image = self.avatars;
}
}];
}
</code></pre>
<p><code>self.imageFiles</code> 数组的顺序正确。
如何确保将下载的图片以与 <code>self.imageFiles</code> 相同的顺序添加到 <code>self.avatars</code> 数组中?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>问题有两部分:(1)显式,如何维护异步操作结果的顺序,(2)使用<code>cell</code>隐含的,如何正确处理支持中的异步请求一个表格 View 。</p>
<p>第一个问题的答案比较简单:保持请求的结果与请求的参数相关联。</p>
<pre><code>// change avatars to hold dictionaries associating PFFiles with images
@property(nonatomic,strong) NSMutableArray *avatars;
// initialize it like this
for (PFFile *imageFile in self.imageFiles) {
];
}
// 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[@"image"];
if (existingImage) return completion(existingImage, nil);
PFFile *pfFile = self.avatars[@"pfFile"];
[pfFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
UIImage *avatar = ;
self.avatars[@"image"] = avatar;
completion(avatar, nil);
} else {
completion(nil, error);
}
}];
}
</code></pre>
<p>好的,第 (1) 部分。对于第 2 部分,您的 <code>cellForRowAtIndexPath</code> 代码必须识别单元格被重用。当异步图像获取发生时,您正在处理的单元格可能已经滚动了。通过不引用完成 block 中的单元格(仅 <code>indexPath</code>)来解决此问题。</p>
<pre><code> // somewhere in cellForRowAtIndexPath
// we're ready to setup the cell's image view
UIImage *existingImage = self.avatars[@"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) {
];
}
}];
}
</code></pre>
<p>重新加载完成 block 中的行将导致再次调用 <code>cellForRowAtIndexPath</code>,除非在随后的调用中,我们将拥有一个现有图像并且单元格将立即得到配置。</p></p>
<p style="font-size: 20px;">关于ios - 解析PFFile下载顺序iOS,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/29867837/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/29867837/
</a>
</p>
页:
[1]