Re: Singletons and Threads
Re: Singletons and Threads
- Subject: Re: Singletons and Threads
- From: "Shawn Erickson" <email@hidden>
- Date: Fri, 14 Sep 2007 19:09:53 -0700
On 9/14/07, Chris Hanson <email@hidden> wrote:
> 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.
You folks aren't look at the rest of the code he posted. He doesn't
need to do any assignment in that block or do sync in that block. Look
at allocWithZone: to see why.
This is basically Apple's example for how to do an "enforced" singleton...
<http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html>
-Shawn
_______________________________________________
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