I’d like to have a singleton in my system but rather than have callers access it via some kind of ‘sharedInstance’ method, I’d like them to be able to be unaware that they are using a singleton, in other words, I’d like the callers to be able to say:
MyClass *dontKnowItsASingleton = [[MyClass alloc] init];
To accomplish this, I’ve tried overriding alloc as follows:
// MyClass.m
static MyClass *_sharedInstance;
+ (id)alloc {
if (!_sharedInstance) {
_sharedInstance = [super alloc];
}
return _sharedInstance;
}
My question is: is this okay? It seems to work, but I’ve never overridden alloc before. Also, if it’s okay, could I always use this technique, rather than dispatch_once approach I have been doing? …
+ (id)sharedInstance {
static SnappyTV *_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
As @H2CO3 mentioned, your method of going about producing singletons is acceptable, however not threadsafe. The more traditional approach is to wrap your assignment and comparison in an
@synchronizedblock so multiple thread access is reduced, however overriding+allocis not the best way of going about implementing an already shaky pattern.