Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa - Singleton object: Where to initialize member variables?

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;
}
like image 639
Yohann T. Avatar asked Aug 21 '09 23:08

Yohann T.


2 Answers

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.

like image 74
Rudi Avatar answered Nov 12 '22 17:11

Rudi


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.

like image 23
Jasarien Avatar answered Nov 12 '22 16:11

Jasarien