Brett
Brett

Reputation: 12007

iOS - Where should I bew releasing my CFImageRef?

I have a method which returns a rotated image:

- (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;
    }
}

Yet, instruments is telling me that rotatedImage: is not being released. I'm running this method a bunch, so the memory build up a lot. Should I be releasing it in the parent method which calls rotateImage:? Or should I release it before rotateImage: passes it back?

Thanks!

Upvotes: 0

Views: 57

Answers (1)

slecorne
slecorne

Reputation: 1718

I would suggest to release the CGImageRef in the parent method calling rotateImage: Moreover in that case you should use the naming convention and rename rotateImage: to createRotateImage: for clarity.

Upvotes: 1

Related Questions