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 18:54:42 +0100
Am 26.11.2005 um 18:21 schrieb David Gimeno Gost:
Yes, you're right, and this is indeed easily fixed, but I think the
+sharedInstance method should also be modified accordingly, because
in that case the shared instance variable and the instance variable
the result of the allocation is assigned to are the same:
Hi,
I realize that I probably should have offered an alternate
approach. Here is one:
+(id) sharedInstance
{
@synchronized(self)
{
static mySharedInstance = nil;
if( mySharedInstance == nil )
mySharedInstance = [[MySingleton alloc] singletonInit];
}
return mySharedInstance;
}
-(id) init
{
id sharedObj = [[self class] sharedInstance];
NSLog(@"Warning: Attempt to traditionally instantiate an object of
class %@. Returning retained instance of singleton.",NSStringFromClass
([self class]));
// -singletonInit takes care of actually initing our single object.
[self release];
return [sharedObj retain];
}
-(id) singletonInit
{
self = [super init];
if( self )
{
// Do init stuff here.
}
return self;
}
Since trying to instantiate a singleton is IMHO a bug, I'm also
echoing a warning, and I don't really care about the overhead caused
by the object that is created and torn down each time through init.
But the advantage of this is that it's fairly simple and clear 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