• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Creating a Singleton Object
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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.

  • Follow-Ups:
    • Re: Creating a Singleton Object
      • From: Oleg Svirgstin <email@hidden>
    • Re: Creating a Singleton Object
      • From: Michael McGonagle <email@hidden>
References: 
 >Creating a Singleton Object (From: Michael McGonagle <email@hidden>)

  • Prev by Date: Re: Toolbar hide/show button
  • Next by Date: Re: Str255 Conversion
  • Previous by thread: Creating a Singleton Object
  • Next by thread: Re: Creating a Singleton Object
  • Index(es):
    • Date
    • Thread