• 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: Best practices with singletons
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Best practices with singletons


  • Subject: Re: Best practices with singletons
  • From: "Glenn L. Austin" <email@hidden>
  • Date: Mon, 09 Jun 2014 07:33:24 -0700

On Jun 8, 2014, at 9:30 AM, William Squires <email@hidden> wrote:

>  Okay, I have several classes in my (somewhat large, and growing) project that implement the singleton pattern via a [<classname> shared<whatever>] class method (and a file-scope static reference) that uses lazy loading to instantiate the singleton the first time a reference is asked for.

You've gotten some very good advice from people for setting up a singleton.

I generally use this kind of pattern:

+ (ClassName*)sharedInstance {
	static ClassName* sSingleton = nil;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		sSingleton = [ClassName new];
	});
	return sSingleton;
}

This way, unless the object itself requires initialization on a specific thread (like CoreData kind of does), then this should be thread-safe and supports lazy initialization.  After all, why initialize something that you'll never use?

--
Glenn L. Austin, Computer Wizard and Race Car Driver         <><
<http://www.austinsoft.com>


_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden


References: 
 >Best practices with singletons (From: William Squires <email@hidden>)

  • Prev by Date: Stupid bindings!%#$% :)
  • Next by Date: Re: Stupid bindings!%#$% :)
  • Previous by thread: Re: Best practices with singletons
  • Next by thread: Re: Best practices with singletons
  • Index(es):
    • Date
    • Thread