Re: Is Apple's singleton sample code correct?
Re: Is Apple's singleton sample code correct?
- Subject: Re: Is Apple's singleton sample code correct?
- From: Shaun Wexler <email@hidden>
- Date: Fri, 2 Dec 2005 12:31:01 -0800
On Dec 2, 2005, at 12:14 PM, Shawn Erickson wrote:
I meant to add that if calling sharedManager is found to be a hot
method then likely the best solution is to simply not do the lazy
allocation but instead allocate the singleton during application
initialization (or in main) so it is ready for callers of
sharedManager.
Of course this assume you have the desire (likely smart to do) to
allow sharedManager to be called from arbitrary threads, if not then
no synchronization is needed and lazy allocation is just fine.
The best/simplest way is to use an immortal-singleton subclass [ie
SKWSingletonObject] which is thread-safe, and create a unique
accessor method for each subclass, caching the ivar locally (and
permanently). Thus an entire subclass might consist of two or more
methods, for example:
+ (void)sharedWhatsit
{
static Whatsit *sharedWhatsit = nil;
if (sharedWhatsit == nil) {
sharedWhatsit = [Whatsit sharedInstance]; // thread-safe accessor!
}
return sharedWhatsit;
}
- (id)init
{
// NOTE: SKWSingletonObject prevents re-init, and with that class
// [super init] simply returns self, so it can be omitted here.
/* custom init code */
return self;
}
--
Shaun Wexler
MacFOH
http://www.macfoh.com
"Problems cannot be solved by the same level of thinking that created
them." - Albert Einstein
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden