I’m trying to write a class that I can subclass to have an instant singleton. Here’s what I have so far. It works until one of its subclasses calls another via sharedInstance which causes a huge loop that eventually runs out of memory.
Any ideas?
static NSMutableDictionary *sharedInstances = nil;
@implementation Singleton
+ (Singleton*)sharedInstance
{
[Singleton initSharedInstances];
Class myClass = [self class];
Singleton * sharedInstance = [sharedInstances objectForKey:myClass];
@synchronized(myClass)
{
if (sharedInstance == nil)
{
sharedInstance = [[myClass alloc] init];
[sharedInstances setObject:sharedInstance forKey:myClass];
}
}
return sharedInstance;
}
+ (void) initSharedInstances
{
if (sharedInstances == nil)
{
sharedInstances = [[NSMutableDictionary alloc] init];
}
}
@end
This sounds like you are describing mutual-recursion. If subclass1 calls subclass2 and subclass2 calls subclass1 then you need to break the loop somewhere, just as with simple self-recursion.
Your
sharedInstanceitself should not cause infinite recursion unless theinitmethod you invoke itself invokessharedInstance…