How to properly implement ARC compatible and `alloc init` safe Singleton class?

来源:互联网 发布:遨龙一号知乎 编辑:程序博客网 时间:2024/05/21 06:28

Apple recommends the strict singleton implementation (no other living object of the same type is allowed) this way:

+ (instancetype)singleton {    static id singletonInstance = nil;    if (!singletonInstance) {        static dispatch_once_t onceToken;        dispatch_once(&onceToken, ^{            singletonInstance = [[super allocWithZone:NULL] init];        });    }    return singletonInstance;}+ (id)allocWithZone:(NSZone *)zone {    return [self singleton];}- (id)copyWithZone:(NSZone *)zone {    return self;}

摘录:http://stackoverflow.com/questions/17809290/how-to-properly-implement-arc-compatible-and-alloc-init-safe-singleton-class

0 0