• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Is Apple's singleton sample code correct?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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
References: 
 >Is Apple's singleton sample code correct? (From: David Gimeno Gost <email@hidden>)
 >Re: Is Apple's singleton sample code correct? (From: Shawn Erickson <email@hidden>)
 >Re: Is Apple's singleton sample code correct? (From: David Gimeno Gost <email@hidden>)
 >Re: Is Apple's singleton sample code correct? (From: Uli Kusterer <email@hidden>)
 >Re: Is Apple's singleton sample code correct? (From: David Gimeno Gost <email@hidden>)

  • Prev by Date: Re: Is Apple's singleton sample code correct?
  • Next by Date: Re: Is Apple's singleton sample code correct?
  • Previous by thread: Re: Is Apple's singleton sample code correct?
  • Next by thread: Re: Is Apple's singleton sample code correct?
  • Index(es):
    • Date
    • Thread