iOS - 我应该在哪里发布我的CFImageRef?

时间:2013-10-16 14:04:53

标签: iphone objective-c core-foundation

我有一个返回旋转图像的方法:

- (CGImageRef)rotateImage:(CGImageRef)original degrees:(float)degrees {
    if (degrees == 0.0f) {
        return original;
    } else {
        double radians = degrees * M_PI / 180;

#if TARGET_OS_EMBEDDED || TARGET_IPHONE_SIMULATOR
        radians = -1 * radians;
#endif

        size_t _width = CGImageGetWidth(original);
        size_t _height = CGImageGetHeight(original);

        CGRect imgRect = CGRectMake(0, 0, _width, _height);
        CGAffineTransform _transform = CGAffineTransformMakeRotation(radians);
        CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, _transform);

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(NULL,
                                                     rotatedRect.size.width,
                                                     rotatedRect.size.height,
                                                     CGImageGetBitsPerComponent(original),
                                                     0,
                                                     colorSpace,
                                                     kCGImageAlphaPremultipliedFirst);
        CGContextSetAllowsAntialiasing(context, FALSE);
        CGContextSetInterpolationQuality(context, kCGInterpolationNone);
        CGColorSpaceRelease(colorSpace);

        CGContextTranslateCTM(context,
                              +(rotatedRect.size.width/2),
                              +(rotatedRect.size.height/2));
        CGContextRotateCTM(context, radians);

        CGContextDrawImage(context, CGRectMake(-imgRect.size.width/2,
                                               -imgRect.size.height/2,
                                               imgRect.size.width,
                                               imgRect.size.height),
                           original);

        CGImageRef rotatedImage = CGBitmapContextCreateImage(context);
        CFRelease(context);

        return rotatedImage;
    }
}

然而,乐器告诉我rotatedImage:没有被释放。我正在运行这种方法,所以内存积累了很多。我应该在调用rotateImage:的父方法中释放它吗?或者我应该在rotateImage:传回之前将其发布?

谢谢!

1 个答案:

答案 0 :(得分:1)

我建议在调用rotateImage:的父方法中释放CGImageRef 此外,在这种情况下,您应该使用命名约定并将rotateImage:重命名为createRotateImage:以便清楚。