search

Home  >  Q&A  >  body text

objective-c - iOS单例创建的一点疑惑

线程安全的单例常用写法,

+(AccountManager *)sharedManager{
        static AccountManager *defaultManager = nil;
        disptch_once_t once;
        disptch_once(&once,^{
          defaultManager = [[self alloc] init];
        });
        return defaultManager;
}

在用的过程中,有点疑惑的点是:
static AccountManager *defaultManager = nil;
这行代码是在sharedManager方法之内的,
在第二次调用sharedManager的时候defaultManager不会被置为nil吗?

天蓬老师天蓬老师2841 days ago848

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-18 09:58:10

    static modified local variables initialize the memory during compilation. It is only initialized once, and there is only one memory in the program, which will not be destroyed until the end of the program. It is stored in static storage area. You can set a breakpoint and try it. Neither once nor defaultManager should be executed. It initializes the memory when compiling.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:58:10

    A variable modified by static will only be initialized once, so it will not be set to nil the second time.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:58:10

    I agree with what was said above. Note the static modifier.

    reply
    0
  • Cancelreply