views:

56

answers:

2

Hi,

Is it best to have static constructors where you alloc the instance in the constructor and you return the instance as auto release, e.g. [String stringWithFormat...] or is it best to have dynamic constructors where you ask the user to alloc first so that he is in charge of releasing? When should you use each?

Cheers

+3  A: 

First, there is no such thing as a "constructor" in Objective-C. Nor is there "static vs. dynamic constructors". You got the C++ taint and it is hampering your ability to understand Objective-C! :)

You'll want to read (and re-read) the memory management guide.

Notably specific to your question, if you have class method like +stringWithFormat:, then that method should return an autoreleased instance. Generally, it would be implemented like:

+ stringWithFoo: (Foo *) aFoo
{
     return [[[self alloc] initWithFoo: aFoo] autorelease];
}

(Simplified slightly to avoid varargs noise).

bbum
Thanks very much. It is true, I am a new objective c programmer with C++ mentality. :)
ar106
+1  A: 
dreamlax
Many thanks. That was exactly what I was after.
ar106