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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With