Question

I have a singleton that is initialized like all singletons, with something like this:

+ (MySingleton *)sharedInstance
{
  static MySingleton *sharedMyInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
        sharedMyInstance = [[MySingleton alloc] init];
  });
  return sharedMyInstance;

}

In my case I want to add some code to initialize the singleton but because sharedInstance is a class method I cannot call instance methods from there.

So I always have to have this pattern:

MySingleton *sing = [MySingleton sharedInstance];
[sing initialize];

Ok, I can do this

MySingleton *sing = [[MySingleton sharedInstance] initialize];

but this will generate another problem because if initializing the singleton is the only thing I want at this point, sing is not being used and this is ugly code.

I suppose I can do simply

[[MySingleton sharedInstance] initialize];

and Xcode will not complain, but this does not sound good.

Is there another way to do this?

Was it helpful?

Solution

Check your code ;-) Specifically the line:

sharedMyInstance = [[MySingleton alloc] init];

You have to implement init and there is where you'll initialize the instance variables of your singleton (AKA shared instance). It will be called the first time the shared instance is used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top