For synchronising singleton creation, you should use the singleton's class as the object to synchronise on. This is my usual pattern:
+(MyObject*) singleton
{
static MyObject* singleton = nil;
@synchronized([MyObject class])
{
if(singleton == nil)
{
singleton = [[MyObject alloc] init];
}
}
return singleton;
}
Points to note:
I've made it a class method. You don't actually have to, it'll work as an instance method.
Normally within class methods when referring to the class, you would use self
(or [self class]
in instance methods). However, that would be wrong here because subclasses would synchronise using a different object to the MyObject class.
I have put the return outside of the @synchronize
block. It is perfectly OK to return from inside the block, but if you do, you get a spurious clang static analyser warning saying the method might not return a value.
Edit
The above pattern is long since obsolete. It's best to use the dispatch_once
pattern
+(MyObject*) singleton
{
static dispatch_once_t onceToken;
static MyObject* singleton = nil;
dispatch_once (&onceToken, ^{
singleton = [[MyObject alloc] init];
});
return singleton;
}