1

If I wanted to create a UIImage for example, what would be the difference in the following two lines of code:

UIImage *img = [UIImage imageWithCGImage:cgImage];

UIImage *img = [[UIImage alloc] initWithCGImage:cgImage];

Is it just a case of "same end, different means"?

1 Answers1

5

imageWithCGImage: returns an autoreleased instance while initWithCGImage: returns an image that you must release yourself. Typically you can count on a class method to return an autoreleased object while any instance init method returns an object you must release.

If you are using ARC code, they basically do the same thing, but see this related question for more information: With ARC, what's better: alloc or autorelease initializers?

Community
  • 1
  • 1
jszumski
  • 7,430
  • 11
  • 40
  • 53
  • 1
    @ConnorLirot you still need to have a pretty good understanding of how memory management works under ARC. So, yes, it does apply. – Mike D Jul 23 '13 at 19:16
  • 1
    Under ARC, the choice of which to use generally doesn't matter. The only time you probably need to care with ARC is when working around an `@autoreleasepool`. – rmaddy Jul 23 '13 at 19:16
  • @rmaddy Could you expand on what could happen when working around an @autoreleasepool? – Connor Lirot Jul 23 '13 at 19:23
  • 2
    @ConnorLirot this question may help: http://stackoverflow.com/questions/9086913/objective-c-why-is-autorelease-autoreleasepool-still-needed-with-arc – jszumski Jul 23 '13 at 19:25
  • @ConnorLirot There was a question a day or two ago that ran into this issue but I can't find it now. It had to do with assigning an autoreleased object inside an `@autorelease` block to a variable declared before the block. The solution was to use `alloc/init` instead of the autoreleased version. – rmaddy Jul 23 '13 at 19:28