使用类别扩展UIImageView会在self.dispatchQueue上引发错误

时间:2012-12-21 13:07:17

标签: iphone categories

我尝试使用新的'loadImageNamed:'方法扩展UIImageView。在这个方法中,我使用dispatchQueue,但XCode抛出一个错误,在'UIImageView'类型的Object上找不到属性'dispatchQueue'。

有人可以给我一个暗示吗?!谢谢!

#import "UIImageView+LazyPicLoad.h"

@implementation UIImageView (LazyPicLoad)

-(void)loadImageNamed:(NSString *)name {
dispatch_async(self.dispatchQueue, ^{
    NSData *imageData;
    if (name) {
        if ([UIScreen mainScreen].scale == 2.0)
            imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"png"]];
        else
            imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:@"png"]];
    }

    CGImageRef decompressedImage = NULL;
    if (imageData) {
        CGDataProviderRef imageDataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)imageData);
        CGImageRef image = CGImageCreateWithPNGDataProvider(imageDataProvider, NULL, NO, kCGRenderingIntentDefault);
        CGContextRef bitmapContext = CGBitmapContextCreate(NULL, CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBitsPerComponent(image), CGImageGetWidth(image) * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
        CGContextDrawImage(bitmapContext, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image);
        decompressedImage = CGBitmapContextCreateImage(bitmapContext);

        CGDataProviderRelease(imageDataProvider);
        CGImageRelease(image);
        CGContextRelease(bitmapContext);
    }

    dispatch_sync(dispatch_get_main_queue(), ^{
        if (decompressedImage)
            self.image = [UIImage imageWithCGImage:decompressedImage];
    });

    if (decompressedImage)
        CGImageRelease(decompressedImage);
});
}

@end

1 个答案:

答案 0 :(得分:1)

这正是问题,UIImageView上没有dispatchQueue属性。如果你想将该块发送到后台,你应该使用它:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // background code
});