Re: Best practices with singletons
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