• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Singletons with ARC
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

  • Follow-Ups:
    • Re: Singletons with ARC
      • From: Greg Parker <email@hidden>
    • RE: Singletons with ARC
      • From: Abdul Sowayan <email@hidden>
  • Prev by Date: Strange behivor when our document-based Cocoa application launch on lion
  • Next by Date: RE: Singletons with ARC
  • Previous by thread: Re: Strange behivor when our document-based Cocoa application launch on lion
  • Next by thread: RE: Singletons with ARC
  • Index(es):
    • Date
    • Thread