是什么导致块不能在ARC下保留引用的Objective-C对象?

我收到一份崩溃报告说:

*** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[__NSMallocBlock__ CGImage]: unrecognized selector sent to instance 0x1fb17f90′

这通常发生在对象已被释放并且另一个对象现在与解除分配的对象位于同一地址时.

这是我的代码(我的应用程序中唯一一个我调用CGImage方法的地方):

@implementation UIImageView (MyApp)

- (void) setImageWithObject:(id)object
{
    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[object URL]];
    __typeof__(self) __weak weakSelf = self;
    [self setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            CGImageRef imageRef = [image CGImage];
            CGRect rect = CGRectMake(0.f, 0.f, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
            CGContextRef bitmapContext = CGBitmapContextCreate(NULL, (size_t)roundf(CGRectGetWidth(rect)), (size_t)roundf(CGRectGetHeight(rect)), CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), CGImageGetColorSpace(imageRef), CGImageGetBitmapInfo(imageRef));
            UIImage *decompressedImage = image;
            if (bitmapContext)
            {
                CGContextDrawImage(bitmapContext, rect, imageRef);
                CGImageRef decompressedImageRef = CGBitmapContextCreateImage(bitmapContext);
                decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
                CGImageRelease(decompressedImageRef);
                CGContextRelease(bitmapContext);
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.image = decompressedImage;
            });
        });
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        NSLog(@"%@", error);
    }];
}

@end

我假设图像对象应该由块自动保留(我正在使用ARC),以便在使用默认优先级队列执行使用它的代码之前,不能释放图像对象.崩溃似乎意味着它没有被保留.

我的假设是错的还是我错过了别的什么?

最佳答案 这与ARC下的UIColor和CGColorRef的行为类似吗?正如这里详述:
http://blog.bignerdranch.com/296-arc-gotcha-unexpectedly-short-lifetimes/

那你在哪里:

CGImageRef imageRef = [image CGImage];

我认为你需要在块中明确地保留它然后明确地释放它,因此ARC不会释放图像引用.

所以:

CGImageRef imageRef = CGImageRetain([image CGImage]);
...
CGImageRelease(imageRef);
点赞