Re: Automagic instantiation of singletons?
Re: Automagic instantiation of singletons?
- Subject: Re: Automagic instantiation of singletons?
- From: Mike Morton <email@hidden>
- Date: Fri, 18 Nov 2005 08:50:32 -0500
Jonathan --
Is there any way to persuade a singleton object to create itself? I
have a few singleton objects that need to exist throughout the
lifetime of the application, and am currently instantiating them in my
application controller's applicationDidFinishLaunching: method.
It would be nice if I didn't have to explicitly do this. My initial
thought was that you could do it through the singletons'
+(void)initialize method - but of course, this isn't called at
application startup - it's only called the first time you try and
access the object, so it still needs to be manually set up.
You could in theory use NSObject’s +load, and I’ve had good luck with
it, but the doc warns “you should avoid using load whenever possible”:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/
ObjC_classic/Classes/NSObject.html#//apple_ref/doc/uid/20000050-load
So I agree with Christian’s suggestion that you have your application
create objects. But instead of having each subclass know how to create
its shared instance, you can add the smarts to NSObject with something
like the code below.
-- Mike
#warning slightly modified from production code, and not tested in this
form
@implementation NSObject (Extensions)
+ (id) sharedInstance;
{
static NSMutableDictionary *cache = nil;
id result;
if (cache == nil)
{
cache = [[NSMutableDictionary dictionary] retain];
}
// Are we in the cache?
result = [cache objectForKey: NSStringFromClass (self)];
if (result == nil)
{
result = [[self alloc] init];
[cache setObject: result forKey: NSStringFromClass (self)];
[result release]; // let the cache (only) retain us
}
return result;
}
@end
_______________________________________________
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