views:

26

answers:

1

I was wondering, what (if any) is the difference between creating objects using:

NSThing *thing = [[NSThing alloc] initWithObject:object];

vs

NSThing *thing = [[NSThing thingWithObject:object] retain];

Is there a difference in how the memory management works? Also, when is it common practice to use one vs the other?

+7  A: 

Allocating and initialising an object is slightly more efficient, because thingWithObject: will do an alloc, then init, then autorelease which you counter with a retain, so you add something to the autorelease pool. The first option only involves an alloc and a init.

Personally, I use the explicit alloc when I want to be clear that the object's lifetime will be handled by me, and I use the convenience methods (thingWithThing:) for any object that I won't need outside of the scope it is created in.

For example, explicitly allocating and initialising within a loop is generally preferred, so that you don't flood the autorelease pool. I also use an explicit alloc+init rather than thingWithThing: + retain for objects that need to survive an iteration of the run loop.

dreamlax