Re: Singletons with ARC
Re: Singletons with ARC
- Subject: Re: Singletons with ARC
- From: Greg Parker <email@hidden>
- Date: Fri, 9 Dec 2011 11:51:10 -0800
On Dec 8, 2011, at 4:06 AM, Ben wrote:
> With the introduction of ARC, I assumed there might be a more suitable implementation out there, and I found this common snippet of code commonly on the net…
>
> + (MyClass *)sharedInstance
> {
> static MyClass *sharedInstance = nil;
> static dispatch_once_t onceToken;
> dispatch_once(&onceToken, ^{
> sharedInstance = [[MyClass alloc] init];
> // Do any other initialisation stuff here
> });
> return sharedInstance;
> }
>
> Which confuses me because surely it should look more like…
>
> static MyClass *sharedInstance = nil;
> + (MyClass *)sharedInstance
> {
> if(sharedInstance==nil){
> static dispatch_once_t onceToken;
> dispatch_once(&onceToken, ^{
> sharedInstance = [[MyClass alloc] init];
> // Do any other initialisation stuff here
> });
> }
> return sharedInstance;
> }
>
> ...else otherwise the second time I access the singleton, MyClass * sharedInstance is declared a second time and set to nill, removing the first instance from memory under ARC?
tl;dr: Delete the `if (sharedInstance == nil)` check. It's not thread-safe.
Back to your original question. The static variable inside the method has the same lifetime as the static variable outside the method. In both cases the variable's storage lives forever and is initialized to zero when the program starts. There's no problem with the variable being created again and set to nil again.
The only difference between the two declarations is that the variable inside the method is visible inside that method only; your other code can't use it. The variable outside the method can be used anywhere in that file. The variable inside the method is preferred when possible because you can't use it by accident in the wrong place.
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
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