Re: Creating a Singleton Object
Re: Creating a Singleton Object
- Subject: Re: Creating a Singleton Object
- From: Oleg Svirgstin <email@hidden>
- Date: Thu, 13 Mar 2003 10:03:31 +0300
Just my two cents:
What I personally like most of all in singletons is that we can make the
most frequent calls into class methods and call them directly.
Assuming the code below (in the message from joar), we might add this:
//it MUST be declared in the @interface, top
+ (int)theValue
{
MySingletonClass* me = [MySingletonClass singletonInstance];
return [me theValue];
}
and call it as [MySingletonClass theValue];
Another point is making the singleton class a repository of global routines
and utilities.
Yet another - making it initialize from NSUserDefaults is the cleanest way
to setup parameters.
I forgot to add "IMHO".
Regards
Oleg
>
From: j o a r <email@hidden>
>
Date: Thu, 13 Mar 2003 00:07:08 +0100
>
To: Michael McGonagle <email@hidden>
>
Cc: email@hidden
>
Subject: Re: Creating a Singleton Object
>
>
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.
_______________________________________________
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.