Singletons with ARC
Singletons with ARC
- Subject: Singletons with ARC
- From: Ben <email@hidden>
- Date: Thu, 08 Dec 2011 12:06:39 +0000
I'm rather confused by the commonly used implementation of singletons. (Ignoring the fact that perhaps I shouldn't be using singletons) I would appreciate you view on this…
Normally I implement a singleton such as..
static MyClass *sharedInstance = nil;
+ (MyClass *)sharedInstance
{
@synchronized(self)
{
if (sharedInstance == nil)
sharedInstance = [[self alloc] init];
}
return(sharedInstance);
}
This has fared me well over the years.
With the introduction of ARC, I assumed there might be a more suitable implementation out there, and I found this common snippet of code commonly on the net…
+ (MyClass *)sharedInstance
{
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
Which confuses me because surely it should look more like…
static MyClass *sharedInstance = nil;
+ (MyClass *)sharedInstance
{
if(sharedInstance==nil){
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
}
return sharedInstance;
}
...else otherwise the second time I access the singleton, MyClass * sharedInstance is declared a second time and set to nill, removing the first instance from memory under ARC?_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden