I would like to have a singleton in my system, but instead of calling the callers through some sharedInstance method, I would like them to not know that they are using a singleton, in other words, I would like the callers to say :
MyClass *dontKnowItsASingleton = [[MyClass alloc] init];
To accomplish this, I tried to override alloc as follows:
// MyClass.m static MyClass *_sharedInstance; + (id)alloc { if (!_sharedInstance) { _sharedInstance = [super alloc]; } return _sharedInstance; }
My question is: is this normal? This seems to work, but I had never redefined alloc before. Also, if everything is in order, can I always use this technique, and not the dispatch_once method that I did? ...
+ (id)sharedInstance { static SnappyTV *_sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _sharedInstance = [[self alloc] init]; }); return _sharedInstance; }
source share