03.为什么用dispatch-once实现单例

面试问到了 自己说到了这点(猜的是线程安全的查了一下确实是这样)

+ (XXXX *)sharedInstance
{
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

dispatch_once是线程安全的,可以确保

参考

http://www.cnblogs.com/hellocby/archive/2012/08/24/2654488.html https://blog.csdn.net/qqMCY/article/details/88648000 单例alloc 、 copy的处理

Last updated