Re: Singletons and Threads
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