我想从NSData加载图像但滚动不顺畅

时间:2014-01-10 06:35:38

标签: ios objective-c xcode

我将图像存储为 base64 NSData在数据库中并从数据库获取并显示在UICollectionView cellForItemAtIndexPath中,因为cell.bgImageView.image图像正在显示但是滚动不顺畅,当我试图从另一个ViewController回来时,它花了太多时间来加载视图。

CODE

NSData *imageData=[[NSData alloc]initWithBase64EncodedString:itemObj.strImage options:NSDataBase64DecodingIgnoreUnknownCharacters];

cell.bgImageView.image = [UIImage imageWithData:imageData];

代码

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

ItemViewController *vc = [[ItemViewController alloc]initWithNibName:@"ItemViewController" bundle:nil];
vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
Item *itemObject = [[Item alloc]init];
itemObject = [arrayOfItems objectAtIndex:indexPath.item];
vc.strItemName = itemObject.strItemName;
vc.strItemDesc = itemObject.strShortDescription;
vc.strImage = itemObject.strImage;
[self presentViewController:vc animated:YES completion:nil];}

上面是下一个viewController和传递值的代码,iam像这样回到CollectionView

- (void)dismiss{
[self dismissViewControllerAnimated:YES completion:nil];

}

2 个答案:

答案 0 :(得分:1)

如果您要设置如下图像,

[UIImage imageWithData:data]

这是同步操作,因此在完成加载之前它会阻塞主线程。 这就是你的滚动视图生涩的原因,因为你阻止了主线程。 尝试在backGround Thread中加载图像,它肯定会解决你的问题。

在backGround线程中加载的代码,

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        UIImage *image =  [UIImage imageWithData:[NSData dataWithContentsOfURL:@"www.example.com"]];
        dispatch_async(dispatch_get_main_queue(), ^{
           cell.myImageView.image = image;
        });
});

答案 1 :(得分:0)

将图片加载代码放入

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        your code here....
  });