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: Uli Kusterer <email@hidden>
- Date: Sat, 26 Nov 2005 14:28:32 +0100
Am 26.11.2005 um 04:50 schrieb David Gimeno Gost:
+ (id) allocWithZone: (NSZone*) zone
{
@synchronized( self ) {
if ( sharedInstance == nil ) {
sharedInstance = [super allocWithZone: zone];
} else {
[sharedInstance retain];
}
}
return sharedInstance;
}
Errm ... good start, but you meant to be @synchronized() on some
other object. If you synchronize to self, two threads create a
"self", and both sync to their own "self"s, so you effectively get
the same result as if you didn't have the @synchronized call in there
at all. You need an explicit NSLock here, or one shared object that
you know you can rely on already existing.
In addition, you *also* need to retain the sharedInstance you get
back from allocWithZone. You need to retain once for the reference
sharedInstance keeps, plus once more for the caller who called
allocWithZone: and expects to get an object they need to release.
With the above code, the following will happen (pseudocode):
foo = [[MySingleton alloc] init] // foo has retainCount 1, and a
second reference to it is in sharedInstance.
[foo doSomething]
[foo release] // foo is released, a stale instance is in
sharedInstance
foo = [[MySingleton alloc] init] // allocWithZone calls retain on
the stale sharedInstance
If you're lucky, it blows up in your face during allocWithZone.
Otherwise you'll have creeping memory corruption and a completely
unrelated crash somewhere in your code.
Cheers,
-- M. Uli Kusterer
http://www.zathras.de
_______________________________________________
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