Re: Singletons?
Re: Singletons?
- Subject: Re: Singletons?
- From: Christian Brunschen <email@hidden>
- Date: Fri, 21 Jun 2002 10:24:29 +0200 (MEST)
On Fri, 21 Jun 2002, The Amazing Llama wrote:
>
Okay, so ObjC has no static variables.
>
>
How do you do a Singleton? What I'm seeing in code on the 'net is to
>
make a global static variable in the .m, but this seems dangerous
>
(someone could change it out from under you, and you can't do anything
>
to stop them) and not at all object oriented (it's just floating out
>
there, polluting the global namespace).
A static variable is only visible in file scope - i.e., only in the file
where it is defined. So a static variable declared & defined in the class
implementation is not visible to anything outside that class. Thus, there
is no pollution of global namespace, nor can anyone else refer to the
variable and change it from underneath you.
@implementation Foo
static Foo *sharedInstance = nil;
+ sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
// ... rest of class ...
@end
... will work fine.
>
There has to be a better way... right?
Nope, because there's nothing wrong with this one :)
Best wishes,
// Christian Brunschen
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.
References: | |
| >Singletons? (From: The Amazing Llama <email@hidden>) |