In Objective C, Usual implementation of singleton

2019-02-20 16:49发布

问题:

When i was going through Singleton design pattern in Objective C, I found lot of people using the below code to create it.

@interface Base : NSObject {} 

+(id)instance;
@end

@implementation Base

+(id) instance
{

static id theInstance = nil;

    if (theInstance == nil)
    {
        theInstance = [[self alloc] init];
    }
    return theInstance;
}

@end

Here i did not get the why do we have to assign the static variable to nil in a method instead it can be declared outside the method and assigned to nil. Because everytime this +instance() method is called, theInstance variable will be assigned to nil. Will it not lose its previous object to which it was pointing to?

I have tried debugging it, surprisingly , it will not point to nil when +instance() method is called. Can anyone explain me whats happening here?

回答1:

static variables only get initialized once, regardless of if they're at global or local scope. In this case, you don't even need the nil - static storage class variables are zero-initialized by default. This declaration:

  static id theInstance;

is enough to be the same as what you have there.