How to properly implement ARC compatible and `alloc init` safe Singleton class?
automatic-ref-counting, ios, objective-c, singleton
Solution
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;
}
Link to the apple documentation (bottom of page, Without ARC)
Problem
I saw thread safe version ``` +(MyClass *)singleton { static dispatch_once_t pred; static MyClass *shared = nil; dispatch_once(&pred, ^{ shared = [[MyClass alloc] init]; }); return shared; } ``` but what would happen if someone just calls `[MyClass alloc] init]` ? How to make it return same instance as the `+(MyClass *)singleton` method?