简体   繁体   中英

CoreGraphics object autoreleased too many times

Upon analyzing my app, Xcode gave me an alert showing that their was a potential leak of an object stored into 'colorSpace' (last line of the code below):

CGContextSaveGState(context);
CGContextAddRect(context, rect);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);

So, I added the following line:

CFAutorelease(context);

And analyzed again. This time, I got an alert in the second line below of "object autoreleased too many times (within a call to 'CGPointMake'):

case SWShadowDirectionUp:
     startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect) - 0.5);
     endPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect) - 0.5);
                break;

Below is where the colorSpace variable is used:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };
NSArray *colors = @[ (__bridge id)self.startColor.CGColor, (__bridge id)self.endColor.CGColor ];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);
CFAutorelease(colorSpace);

However, I'm not sure what exactly is going wrong, or how to fix it. Does anyone have any suggestions?

I'm unsure what you've done wrong in your source because you haven't included the entire scope of colorSpace . Here is what I have tried and the static analyzer does not complain:

- (UIImage *)decompressImage:(UIImage *)image {
  CGImageRef imageRef = image.CGImage;
  size_t width = CGImageGetWidth(imageRef);
  size_t height = CGImageGetHeight(imageRef);

  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8,
                                               width * 4, colorSpace,
                 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
  CGColorSpaceRelease(colorSpace);
  if (!context)
    return image;

  CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
  CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
  CGContextRelease(context);

  UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
  CGImageRelease(decompressedImageRef);
  return decompressedImage;
}

Just make sure you have a Release for every Create before the end of the scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM