-1

I'm confused on how to implement a singleton in objective-c.

I read this post on stackoverflow and was confused by the code shown as the right answer.

How do I implement an Objective-C singleton that is compatible with ARC?

This code is from the post I link to above.

+ (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;
}

What I don't understand is this single line below.

    static MyClass *sharedInstance = nil;

Why does it need to assign "nil" to static variable within the method? If this line is on the top within sharedInstance method, every time it is called, the static variable becomes nil. And because "despatch_once" is only called once, I think this method always return nil after this method is called once.

Could anyone please help me understand how this thing works?

Does the first line of this method also get ignored after the second call?

Community
  • 1
  • 1
crzyonez777
  • 1,789
  • 4
  • 18
  • 27
  • 1
    A `static` variable is only initialized once. It only gets set to `nil` once, never again. – rmaddy Mar 11 '14 at 04:27
  • possible duplicate of [Create singleton using GCD's dispatch\_once in Objective C](http://stackoverflow.com/questions/5720029/create-singleton-using-gcds-dispatch-once-in-objective-c) – CoolMonster Mar 11 '14 at 04:39

1 Answers1

3

Any static variable in any class is created only once, and is shared between all instances of the same class

But there's another use of static variables, and that is a static variable inside a function, which is the case of your example. A static variable inside a function is a variable who's value is preserved among subsequent calls.

- (int)addOne
{
    static int i;
    i++;
    return i;
}

Here, even when i is a local variable, i will preserve it's value from the previous call. But how do you initialize such a variable?? Well, you do it like this

static int i=10;

The initialization is only executed the first time the function is called, and is skipped in all subsequent calls.

Merlevede
  • 8,140
  • 1
  • 24
  • 39