开发者

Objective C static vs. dynamic constructors

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


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).


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 that alloc+initWithFormat:+release may 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 a release later), 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, NSWindow is not an class that you create and delete instances of frequently, so there are no convenience methods for creating NSWindow instances, you have to go through the alloc+init route (in fact, NSWindow is 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜