views:

1468

answers:

4

Hello people!

I was wondering where is the best place to initialize members of the singleton class.

I'm using Apple fundamental guide singleton implementation. Could you please pinpoint at what line the inits happen? The code is the following:

static MyGizmoClass *sharedGizmoManager = nil;

+ (MyGizmoClass*)sharedManager
{
    @synchronized(self) {
        if (sharedGizmoManager == nil) {
            [[self alloc] init]; // assignment not done here
        }
    }
    return sharedGizmoManager;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self) {
        if (sharedGizmoManager == nil) {
            sharedGizmoManager = [super allocWithZone:zone];
            return sharedGizmoManager;  // assignment and return on first allocation
        }
    }
    return nil; //on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (unsigned)retainCount
{
    return UINT_MAX;  //denotes an object that cannot be released
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}
+8  A: 

It's as with usual classes - add this above the block:

-(id)init {
  if (self = [super init]) {
     // do init here
  }

  return self;
}

It will be called when singleton is accessed first time.

Rudi
if i create that init method, then it would accessible straight without passing through the sharedManager, right?Now if i make it private, that won't overide the init() method, right?
Yohann T.
Yes, it's accessible directly, but I don't think it should be - singleton will make sure it's called first time it's needed. You just call [[MySingletonClass sharedClass] message] as usual...
Rudi
+1, as noted by Jon Hess you generally should not overload all these methods unless you really absolutely have to ensure that there is one and only one instance of this object. That's pretty rare in practice. Generally you just want to make it easy to access a shared one, and for that you just need to implement a +sharedInstance (or +sharedManager, or whatever) method that returns a static instance, and not worry if a caller explicitly requests a unique instance.
Rob Napier
How are Apple developers doing it with their own singletons? There has to be a way to prevent users to access the init() method.
Yohann T.
Okay, you got to read the article posted on this page by Jon Hess, it basically explains it all.
Yohann T.
+1  A: 

You can initialise them in the init method, like any other class.

However, be mindful that if your singleton contains member state, it may no longer be threadsafe. Since a singleton is accessible anywhere in the app at any time, it may be accessed from different threads.

Jasarien
A: 

You can still specify:

- (id)init;

...for this class. It will only get called once (when the singleton is first instantiated) but that would be the proper place to do any initialization.

fbrereto
A: 

See this thread

Jordan