help-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Alloc/dealloc etiquette


From: Michael Ash
Subject: Re: Alloc/dealloc etiquette
Date: Sun, 18 Feb 2007 14:51:43 -0600
User-agent: tin/1.6.2-20030910 ("Pabbay") (UNIX) (FreeBSD/4.11-RELEASE-p20 (i386))

In comp.lang.objective-c Jens Ayton <VFNZRCIMVBRO@spammotel.com> wrote:
> Michael Ash:
>> 
>> You should never override +alloc. +alloc is just a convenience method for 
>> +allocWithZone: with a NULL argument, so if you need to override one, you 
>> should override +allocWithZone:. However, there is basically never a 
>> reason to do this. Allocating objects is generally something where the 
>> base class does it right and you should have no need to modify its 
>> behavior when doing so.
> 
> The chapter ?Creating a Singleton Instance? of Apple?s ?Cocoa
> Fundamentals Guide?[1] presents a template implementation of a singleton
> which ensures uniqueness in +allocWithZone:. While it?s possible to
> ensure singleton status in -init, and the singleton pattern itself can
> be and has been criticised, using the template from Apple?s
> documentation is a reasonably reasonable case where overriding
> +allocWithZone: is motivated. :-) (It does, however, call [super
> allocWithZone: in the case where allocation actually happens.)

I personally prefer doing this sort of thing by overriding -init to do a 
[self release] and return the singleton, just because it seems cleaner. It 
fits better with the documented functionality of the methods; 
+allocWithZone: is documented as returning a new instance, but -init is 
explicitly documented as possibly returning some other object. Lastly, 
overriding -init means that you only have the "does the singleton exist?" 
logic in one place; if you override +allocWithZone:, then you also have to 
ask this question in -init to prevent your object from being 
double-initialized.

But all in all it's not a big difference, and overriding +allocWithZone: 
is a perfectly legitimate way to accomplish this. That's why I included 
the qualifier on "never", after all. :)

-- 
Michael Ash
Rogue Amoeba Software


reply via email to

[Prev in Thread] Current Thread [Next in Thread]