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"?

0

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

5 Comments

@ConnorLirot you still need to have a pretty good understanding of how memory management works under ARC. So, yes, it does apply.
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 Could you expand on what could happen when working around an @autoreleasepool?
@ConnorLirot this question may help: stackoverflow.com/questions/9086913/…
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.