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: Andy Lee <email@hidden>
- Date: Tue, 29 Nov 2005 20:01:59 -0500
On Nov 29, 2005, at 7:15 PM, David Gimeno Gost wrote:
On 29 Nov 2005, at 20:03, Andreas Mayer wrote:
AFAIK it's not only singletons where you can't depend on dealloc
being called before the application quits.
Therefore it might be necessary to listen to the appropriate
notifications to do your cleanup; singleton or not.
I know. I never meant otherwise. But when you get the notification
you must call some method to do the clean up.
I started to compose a post saying exactly this, but gave up when I
saw I was starting to ramble.
What I'm saying is that, telling an object to release the resources
it manages is semantically identical to destroying it in most cases
(i.e. the existence of the object has no purpose after those
resources have been released), so, instead of sending it a -
doCleanUp message, I might as well send it a -release message.
I started to say something like this too, but it occurred to me this
doesn't work if your object is in a retain cycle. If you want -
dealloc to get called, you'll need some kind of -
tearDownMyConnections method to break the retain cycle. And if
you're going to add a special method meant to be called at the end of
the app, then you might as well have it do cleanup as well.
Whichever approach you choose, make sure you document the fact that
resource cleanup should be done when the app terminates, and document
how it should be done.
And there are other nasty side effects too, such as that you must
write the -init method to take into account the possibility that it
gets invoked more than once for the same object.
If you want to program really defensively, you should probably add
that safeguard to -init in any case. Nothing prevents the user of
your class from sending -init at any time to any instance, singleton
or not.
Note that the sample code provided by Apple will likely be copied
and used by many novices without really understanding its nasty
side effects nor why are all those methods actually being
overridden. I could understand the current situation if there was a
trade-off that justified writing the singleton that way, but there
is none.
I didn't look closely at the whole code example, but I agree that
mucking with the semantics of +allocWithZone:, -init, *and* -dealloc
is not desirable unless there's a tradeoff.
--Andy
_______________________________________________
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