title: Releasing renderInContext result within a loop
body: <p>I have a method which is called in a loop, that looks something like this:</p>
  
  <pre><code>NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  UIImageView *background = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, PAGE_WIDTH, PAGE_HEIGHT)];
  background.image = backgroundImg;
  
  for (UIView *view in viewArray)
  {
      [background addSubview:view];
  }
  
  UIGraphicsBeginImageContext(background.frame.size);
  [background.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  for (UIView *view in background.subviews)
      [view removeFromSuperview];
  
  background.image = nil;
  [background release];
  [image retain];
  [pool drain];
  [image autorelease];
  return image;
  </code></pre>
  
  <p>However, according to Instruments Memory Monitor, the memory usage goes up and up, and never comes down until the end of the loop. (It crashes.)</p>
  
  <p>If I replace the UIGraphicsBeginImageContext to UIGraphicsEndImageContext with </p>
  
  <p>UIImage *image = someotherimage;</p>
  
  <p>then the memory does not spike, but is allocated and reduces on every iteration of the loop, as I would expect, due to the Autorelease pool. (It doesn't crash)</p>
  
  <p>And if I just comment out the renderInContext line it works fine. (Doesn't crash)</p>
  
  <p>So it looks as if renderInContext is holding onto the image somehow - how can I get it to release it? Or any alternative suggestions please :)?</p>