开发者

IPHONE: Question about releasing a variable

Consider this pseudo code:

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

image开发者_C百科PX = [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?


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.


Instead of

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

Use

[UIImage imageWithContentsOfFile:...bla bla

The latter will be autoreleased.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜