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?
Allocating and initialising an object is slightly more efficient, because
thingWithObject:will do analloc, theninit, thenautoreleasewhich you counter with aretain, so you add something to the autorelease pool. The first option only involves anallocand ainit.Personally, I use the explicit
allocwhen 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+initrather thanthingWithThing:+retainfor objects that need to survive an iteration of the run loop.