My singleton accessor method is usually some variant of:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
What could I be doing to improve this?
Another option is to use the +(void)initialize
method. From the documentation:
The runtime sends
initialize
to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends theinitialize
message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
So you could do something akin to this:
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}