Is there a way to create a Singleton pattern with objective-c, which would enable the client code to get a shared instance of any of it's subclasses?
I tried:
@interface Base : NSObject {}
+(id)instance;
@end
@implementation Base
static id _instance;
+(id)instance {
if (!_instance) {
_instance = [[self alloc] init];
}
return _instance;
}
@end
But calling any subclass's [AmazingThing instance]
only returns the first instance created through this mechanism, no matter what type the _instance
is. Any clean workarounds?
Edit
I realized (while replying to a deleted answer) that I can do what I was looking for by changing the implementation to be:
static NSMutableDictionary *_instances;
+(id)instance {
if (!_instances) {
_instances = [[NSMutableDictionary alloc] init];
}
id instance = [_instances objectForKey:self];
if (!instance) {
instance = [[self alloc] init];
[_instances setObject:instance forKey:self];
}
return instance;
}
It now works as expected. Still, I'm interested to know if there's a better way to do this.