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:So you could do something akin to this:
Just wanted to leave this here so I don't lose it. The advantage to this one is that it's usable in InterfaceBuilder, which is a HUGE advantage. This is taken from another question that I asked:
I've rolled singleton into a class, so other classes can inherit singleton properties.
Singleton.h :
Singleton.m :
And here is an example of some class, that you want to become singleton.
The only limitation about Singleton class, is that it is NSObject subclass. But most time I use singletons in my code they are in fact NSObject subclasses, so this class really ease my life and make code cleaner.
For an in-depth discussion of the singleton pattern in Objective-C, look here:
Using the Singleton Pattern in Objective-C
My way is simple like this:
If the singleton is initialized already, the LOCK block will not be entered. The second check if(!initialized) is to make sure it is not initialized yet when the current thread acquires the LOCK.
A thorough explanation of the Singleton macro code is on the blog Cocoa With Love
http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html.