The accepted answer, although it compiles, is incorrect.
+ (MySingleton*)sharedInstance
{
@synchronized(self) <-------- self does not exist at class scope
{
if (sharedInstance == nil)
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}
Per Apple documentation:
... You can take a similar approach to synchronize the class methods of the associated class, using the Class object instead of self.
Even if using self works, it shouldn't and this looks like a copy and paste mistake to me.
The correct implementation for a class factory method would be:
+ (MySingleton*)getInstance
{
@synchronized([MySingleton class])
{
if (sharedInstance == nil)
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}