Question

Consider this pseudo code:

// an image is initialized
UIImage *imagePX = [[UIImage alloc]initWithContentsOfFile:... bla bla

imagePX = [self rotateImage:imagePX]; //A
[self doStuff:imagePX]; //B

Then I have the rotateImage method:

- (UIImage*) rotateImage:(UIImage*)source {
  ... rotate the image... draw on context...
  [source drawInRect... bla bla
  ...

  UIImage *rotatedImage =  UIGraphicsGetImageFromCurrentImageContext();

  return rotatedImage;
}

My question is: imagePX was never released. As the image is passed to the method RotateImage, I thought I could simply release it, after using it on the command [source drawInRect...], as I would return a rotatedImage on the method, but if I do that, the program will crash, because the variable imagePX should exist so line A can evaluate.

My other problem is that the image will be forwarded on B to another routine. So, what's the best way to make it work without losing track of imagePX and leaking?

What's the best approach?

Was it helpful?

Solution

Instead of

[[UIImage alloc]initWithContentsOfFile:... bla bla

Use

[UIImage imageWithContentsOfFile:...bla bla

The latter will be autoreleased.

OTHER TIPS

There is no need to allocate an instance of UIImage. imageWithContentsOfFile is a static method, and can be called on the class itself.

Since imageWithContentsOfFile does not include the terms alloc, new, or copy the returned object (by convention) is not retained, and will be autoreleased at the first drain of the autorelease pool.

Conversely, if you ever run into a similar situation where you can't figure out why you are receiving EXC_BAD_ACCESS errors when trying to access this object, it's likely been released too soon. In those cases, you will want to do a manual retain/release within the scope of this class.

What about [UIImage imageNamed:@""]? No alloc, no need to release)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top