Patroclus
Patroclus

Reputation: 1232

Why self=[super init] ensure the singleton pattern?

I read many implementation of singleton pattern in Objective-C, and lots of the code contain such a line in the init method:

if ((self = [super init])) {
   ...
}

And according to this page, which is referred by many questions regarding [super init]: https://www.cocoawithlove.com/2009/04/what-does-it-mean-when-you-assign-super.html

self = [super init] "always returns the singleton instead of any subsequent allocation".

But why? The following is my implementation of a shared singleton

#pragma mark -
#pragma mark Constructors

+ (VoiceProfileManager*)sharedManager {
    static VoiceProfileManager *sharedManager = nil;
    //Executes a block object once and only once for the lifetime of an application.
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedManager = [[VoiceProfileManager alloc] init];
    });
    return sharedManager;
}

- (id)init {
    if ((self = [super init])) {
    }
    return self;
}

@end

Upvotes: 1

Views: 56

Answers (2)

Itachi
Itachi

Reputation: 6070

It's not the init method but the dispatch_once function to let you build the singleton instance.

static dispatch_once_t once;
dispatch_once(&once, ^{
    // every code here will be executed only once!
});

The first line initializes a global static variable called once, it has a constant value after dispatch_once function execute once.

You could assume that there is a global variable pool for the once value, when it executes in the second time, it checks whether the once value exists in the pool and skip the block execution if it is.

So why the first line initializes the once variable only one time? Check the static keyword in C language.

Good luck!

Upvotes: 1

ericl
ericl

Reputation: 321

The external page you referenced says [super init] (not self = [super init] as in your question) "always returns the singleton instead of any subsequent allocation"

So, [super init] could return a different object. In that case, "continuing to initialize the returned object if it changes is a mistake"

Upvotes: 0

Related Questions