使用GCD接收内存警告的图像加载

时间:2013-03-22 13:51:20

标签: ios multithreading grand-central-dispatch alassetslibrary nsautoreleasepool

我正在使用AssetsLibrary开发照片库应用程序来加载我的设备照片。当在另一个VC中呈现随机图像时,我注意到以下情况:我的完整res图像需要大约1或2秒加载到imageView上(比原始photosApp长得多),我也从日志中获取“已接收”加载一些图像后的“内存警告”。如果我将我的表示设置为fullScreenImage,警告会停止,但我不想这样做。为了在视图上获得流畅的性能和高质量的图像,我必须改变什么?

这是代码,希望你能告诉我这是什么问题:

这是我希望在屏幕上显示图像的VC

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"%@",assetsController);

    detailImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:detailImageView];
    detailImageView.image = smallImage; //small image is my asset thumbnail and is passed as an argument in my init function

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

        ALAsset *asset = [assetsController.albumPics objectAtIndex:assetsController.index];
        ALAssetRepresentation *representation = [asset defaultRepresentation];

        bigImage = [[UIImage imageWithCGImage:[representation fullResolutionImage]]retain];

        dispatch_async(dispatch_get_main_queue(), ^{

            detailImageView.image = bigImage;

        });
        [pool release];
    });
}

更新1

    {
        UIImageView *detailImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:detailImageView];
        detailImageView.image = smallImage;


        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

            NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

            ALAsset *asset = [assetsController.albumPics objectAtIndex:assetsController.index];
            ALAssetRepresentation *representation = [asset defaultRepresentation];

            UIImage *bigImage = [UIImage imageWithCGImage:[representation fullResolutionImage]];


            dispatch_async(dispatch_get_main_queue(), ^{

                detailImageView.image = bigImage;

            });
            [pool release];

        });
}

enter image description here

1 个答案:

答案 0 :(得分:0)

bigImage是实例变量吗?它是否用于除此之外的任何地方?如果它没有在其他任何地方使用,那么它应该是一个局部变量,你不应该保留它。如果它是您保留的实例变量,则需要在为其分配新值之前释放先前的值。

同样的讨论适用于detailImageView