iphoneiosmemory-managementcgimageautorelease

When to release the UIImage?


I use the following code to draw a subimage

UIImage* subIm = getSubImage( large, rect );
[subIm drawInRect:self.bounds];

where getSubImage is defined as follows

    UIImage* getSubImage(UIImage* uim, CGRect rc){
      CGImageRef imref  = CGImageCreateWithImageInRect(uim.CGImage, rc); 
      UIImage*   sub = [UIImage imageWithCGImage:imref];
      CGImageRelease(imref);
        NSLog(@"subimage retainCount=%d", [sub  retainCount]); // is 1
      return sub;
   }//getSubImage

Is the code correct?

Is it safe to "CGImageRelease" imref?

Has sub "CGImageRetained" imref?

Should I release subIm (I get an error if I do)?

Is subIm contained in the autorelease-pool, and , if so, how do I know this?

In general, can one check if an object is contained in the autorelease pool (for debugging purpose)?


Solution

  • SubIm is enrolled in the AutoRelease Pool because this object is in fact created by the class method imageWithCGImage and that the rule is that instances created by class methods should always return autoreleased instances.

    The code is correct though I don't understand why your are using the C syntax instead of the Obj-C syntax to define your function