Re: Creating a Singleton Object
Re: Creating a Singleton Object
- Subject: Re: Creating a Singleton Object
- From: j o a r <email@hidden>
- Date: Thu, 13 Mar 2003 00:07:08 +0100
Please look in the list archives! There are tons of threads on this and
similar topics.
Here is one simple implementation I posted a couple of days ago:
@interface MySingletonClass : NSObject
{
@private
int _someValue;
}
+ (id) singletonInstance;
- (int) theValue;
- (void) setTheValue:(int) value;
@end
@implementation MySingletonClass
+ (id) singletonInstance
{
static id singletonObject = nil;
if (singletonObject == nil)
{
singletonObject = [[self alloc] init];
}
return singletonObject;
}
- (int) theValue
{
return _someValue;
}
- (void) setTheValue:(int) value
{
_someValue = value;
}
@end
You use the singleton from any other object that knows about it (ie.
imports the header file) like this:
[[MySingletonClass singletonInstance] setValue: 0];
You can of course name the singleton access method anything you like
(it doesn't have to be "singletonInstance"), in Cocoa names beginning
with shared* and default* are common.
j o a r
On Wednesday, Mar 12, 2003, at 23:04 Europe/Stockholm, Michael
McGonagle wrote:
I am trying to implement a Document-based program and have an object
that I want to share among all these document objects. How do I create
an object that only creates a single instance, as well as providing
all other objects access to that "global" instance?
If this sounds like a big mistake in design, please offer some other
suggestions.
_______________________________________________
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.