Re: Is Apple's singleton sample code correct?
Re: Is Apple's singleton sample code correct?
- Subject: Re: Is Apple's singleton sample code correct?
- From: Shawn Erickson <email@hidden>
- Date: Sat, 26 Nov 2005 08:12:18 -0800
On Nov 26, 2005, at 7:53 AM, David Gimeno Gost wrote:
On 26 Nov 2005, at 09:14, Shawn Erickson wrote:
Consider reviewing what I use...
<http://www.cocoadev.com/index.pl?FTSWAbstractSingleton>
I don't get it, sorry.
I was answering in the point of view of an implementation like the
one Apple outlines in the documentation you noted. The one I use
moves init out to an initSingleton method that is private and not
advertised in headers (note the version of the website was
simplified, normally I have initSingleton in a private category in
the .m file).
I still don't get it.
Yes, you avoid the problem of repeatedly calling -init by not
allowing it, but then you don't allow instances of the singleton to
be obtained by means of [[alloc] init] either and thus your
singletons cannot be created as any other object, which I thought
was the whole point of overriding +allocWithZone:.
You can override allocWithZone for any number of reasons...
In this case the point of overriding allocWithZone is some defensive
programming for a pathway that callers shouldn't be using, they
should be using some class method that gets them the shared instance
(the later would be the documented to users of of the class as the
way to get an instance and no init method would be listed). Since
this is a class method that gets them an instance and doesn't have
"alloc" in its name the caller isn't responsible for release it. Thus
it follows the normal memory contract and can give the caller a hint
a shared instance exists (which may allow them to optimize their
code, documentation can do the same). It of course also relies on
overriding retain/release (and others as needed) to allow normal use
of retain and release without affecting the existence of the singleton.
You don't have to implement it this way (wasn't attempting to imply
it was)... and you can easily argue it is a more complex and/or
unneeded way to implement a singleton but it is still a valid and
functional way to do it.
If you would like Apple to list alternate implementations in their
documentation about the singleton pattern file a documentation defect.
-Shawn
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden