线程安全的单例常用写法,
+(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吗?
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.
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.