In Objective C, Usual implementation of singleton design pattern contains “static id theInstance = nil” in a method, why not outside?

瘦欲@ 提交于 2019-12-19 11:52:44

问题


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.



来源:https://stackoverflow.com/questions/16932652/in-objective-c-usual-implementation-of-singleton-design-pattern-contains-stati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!