• 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
Re: Singletons and Threads
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Singletons and Threads


  • Subject: Re: Singletons and Threads
  • From: Chris Hanson <email@hidden>
  • Date: Fri, 14 Sep 2007 19:05:34 -0700

On Sep 14, 2007, at 6:49 PM, PGM wrote:

You are not assigning the newly inited object to the sharedMPInterpreter, so you are in fact returning nil. Leaving aside the @synchronized bit, I would have written it like this:

+ (MPInterpreter *) sharedInterpreter { static MPInterpreter *sharedInstance = nil;

   if (sharedInstance == nil)
   {
		sharedInstance = [[[self class] alloc] init];
   }

   return sharedInstance;
}

You also need synchronization, to ensure that the shared instance is only created once.


+ (MPInterpreter *)sharedInterpreter {
    static MPInterpreter *sharedInterpreter = nil;

    @synchronized (self) {
        if (sharedInstance == nil) {
            sharedInstance = [[[self class] alloc] init];
        }
    }

    return sharedInterpreter;
}

The other advantage of this is that you can avoid the wacky override of +allocWithZone:, thus allowing your code to support instantiating new, individual MPInterpreter instances in your unit tests.

Seriously, the "I want to enforce singleton-hood" pattern is generally something to be avoided. You're usually better off just providing a +sharedBlah method and a comment in your class header file (along with no designated initializer) than trying to force there to only ever be one instance of a particular class.

  -- Chris

_______________________________________________

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 and Threads
      • From: "Shawn Erickson" <email@hidden>
References: 
 >Singletons and Threads (From: "Randall Wood" <email@hidden>)
 >Re: Singletons and Threads (From: "Clark Cox" <email@hidden>)
 >Re: Singletons and Threads (From: "Randall Wood" <email@hidden>)
 >Re: Singletons and Threads (From: PGM <email@hidden>)

  • Prev by Date: Re: Singletons and Threads
  • Next by Date: Re: Singletons and Threads
  • Previous by thread: Re: Singletons and Threads
  • Next by thread: Re: Singletons and Threads
  • Index(es):
    • Date
    • Thread