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 protected]     Runtime Wrangler


_______________________________________________

Cocoa-dev mailing list ([email protected])

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to