UICollectionView从文档目录加载多个图像时卡住

时间:2018-08-07 10:21:59

标签: ios objective-c asynchronous uicollectionview

我正在加载30-50张以上的图像,这些图像存储在文档目录中。它们所有图像都立即加载到SELECT t.name FROM table t INNER JOIN tablegroups tg ON tg.tablegroup_id = t.tablegroup_id ORDER BY tg.sort_id, t.sort_id; 中,但是此时滚动collectionView时将卡住。

collectionView

我还尝试了以下调度块

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"ImageCell";
    ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    //Load image from document  directory
    NSString *imageName = [arrCollection objectAtIndex:indexPath.row];
    NSString *imagePath = [NSString stringWithFormat:@"%@/%@",(AppObj).imagefolderPath, imageName];
    UIImage *localImg = [[UIImage alloc]initWithContentsOfFile:imagePath];

    cell.imgSketch.image = localImg;

    cell.txtName.text = [NSString stringWithFormat:@"%@",[imageName stringByReplacingOccurrencesOfString:@".png" withString:@""]];

    cell.layer.masksToBounds = YES;
    return cell;
}

请建议我解决此问题的任何解决方案。

预先感谢

4 个答案:

答案 0 :(得分:1)

您可以使用SDWebImage来显示文档目录中的图像。

[cell.imgSketch sd_setImageWithURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",(AppObj).imagefolderPath,[arrCollection objectAtIndex:indexPath.row]]]];

注意:在创建NSURL的对象时使用fileURLWithPath,因为它是文件的路径。

答案 1 :(得分:0)

我建议仅从cellForRowAt

中加载一次所有图像
NSMutableArray*images; // every instance is of type UIImage not imageName

代替此

UIImage *localImg = [[UIImage alloc]initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",(AppObj).imagefolderPath,[arrCollection objectAtIndex:indexPath.row]]];

注意:此方法initWithContentsOfFile在mainQueue中运行,因此这是卡住的主要原因

答案 2 :(得分:0)

我建议将图像加载操作移至后台线程。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
   UIImage* localImage = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",(AppObj).imagefolderPath,[arrCollection objectAtIndex:indexPath.row]]];    
   dispatch_async(dispatch_get_main_queue(), ^{
      cell.imgSketch.image = localImage;
   });
});

答案 3 :(得分:0)

如果使用大图像,则collectionview / tableview单元将闪烁。尝试使用低尺寸图片或在后台队列中的cellForItemAtIndexPath上创建一个图片。

您可以通过将图像缓存在阵列中来提高性能。 注意:如果容量增加限制,请尝试对其进行清洁。

cell.imgSketch.image = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

     UIImage *localImg = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", (AppObj).imagefolderPath, [arrCollection objectAtIndex:indexPath.row]]];

     NSData *imgData = UIImageJPEGRepresentation(localImg, 0.5);
     localImg = [UIImage imageWithData:imgData];

     dispatch_async(dispatch_get_main_queue(), ^{
         ImageCell *imageCell = [collectionView cellForItemAtIndexPath:indexPath];
         if (imageCell) {
             cell.imgSketch.image = localImg;
         }
    });
});