Reputation: 157
what is the difference between these singleton implementations:
declaring static instance outside the sharedManager functions
@implementation MyManager
static MyManager * manager = nil;
+(instancetype)sharedManager
{
@synchronized(self) {
if(manager==nil){
manager = [[MyManager alloc]init];
}
return manager;
}
}
2.
declaring static instance inside the sharedManager function
@implementation MyManager
+(instancetype)sharedManager
{
static MyManager * manager = nil;
@synchronized(self) {
if(manager==nil){
manager = [[MyManager alloc]init];
}
return manager;
}
}
@end
4.
+ (instancetype)sharedManager {
static MyManager *singleton=nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
singleton = [[self alloc] init];
});
return singleton;
}
Upvotes: 1
Views: 67
Reputation: 385890
You should make it a static variable inside the accessor method. This prevents you from accidentally accessing it before it's been properly initialized.
The modern way to initialize a singleton safely is like this:
+ (instancetype)sharedManager {
static MyManager *singleton;
static dispatch_once_t once;
dispatch_once(&once, ^{
singleton = [[self alloc] init];
});
return singleton;
}
dispatch_once
is significantly faster than @synchronized
if the once-block has already been performed.
Upvotes: 2