Re: Creating a Singleton Object
Re: Creating a Singleton Object
- Subject: Re: Creating a Singleton Object
- From: Fritz Anderson <email@hidden>
- Date: Wed, 12 Mar 2003 18:20:08 -0600
- Resent-date: Wed, 12 Mar 2003 18:52:09 -0600
- Resent-from: Fritz Anderson <email@hidden>
- Resent-message-id: <email@hidden g>
- Resent-to: email@hidden
On Wednesday, March 12, 2003, at 04:04 PM, 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?
There are two approaches. Both require some cooperation from the
class's client.
One is to have a class method return the singleton; see +sharedInstance
in the dashed-off code below. The client has to know to get the
instance from that method.
The other is to implement the -init* instance methods so that the
instance returned is always the singleton. The client has to take care
always to use the object pointer that comes from the -init* method, and
not from the +alloc.
-- F
static MySingletonClass * sSingleton = nil;
@implementation MySingletonClass
+ (void) initialize
{
if (! sSingleton)
sSingleton = [[MySingletonClass alloc] initPrivate];
}
+ (MySingletonClass) sharedInstance
{
return [[sSingleton retain] autorelease];
}
- (id) initPrivate
{
// Here do the initialization for the singleton instance.
// Don't publish or use this method otherwise
return self;
}
- (id) init
{
NSAssert(self != sSingleton, @"Should never send init to the singleton
instance");
[self release];
[sSingleton retain];
return sSingleton;
}
@end
--
Fritz Anderson - Consulting Programmer - Chicago, IL
Mail: <email@hidden>
Risumi: <
http://resume.manoverboard.org>
_______________________________________________
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.