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
I’m not sure whether “static” and “dynamic” are the appropriate terms.
[NSString stringWithFormat:...]is a convenience method. If you want a formatted string that you aren’t going to keep for very long, you can use this convenience method to avoid the clutter thatalloc+initWithFormat:+releasemay introduce into your [otherwise simple] code.[[NSString alloc] initWithFormat:...]is sometimes clearer to the reader that the lifetime of this object will be handled explicitly (i.e. with areleaselater), although, I have found it is not uncommon to encounter a[[[NSString alloc] initWithFormat:...] autorelease]in places.When you are designing a class, you should determine whether instances of your class are intended to be used frequently/quickly rather than long-term (or both). If you consider that your classes can be used frequently or quickly, then providing the convenience method will help reduce clutter and simplify the code that utilises the class.
For example,
NSWindowis not an class that you create and delete instances of frequently, so there are no convenience methods for creatingNSWindowinstances, you have to go through thealloc+initroute (in fact,NSWindowis not normally an class that you have to create instances of manually anyway). On the other hand, strings, arrays, dictionaries, sets, and so on, these are all things that are often created and discarded frequently, so they all have convenient methods that make creating them and managing them easier.