objective-c - iOS单例创建的一点疑惑
天蓬老师
天蓬老师 2017-04-18 09:56:10
0
3
806

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

+(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吗?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
刘奇

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.

Peter_Zhu

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

大家讲道理

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!