nitinsh99 nitinsh99 - 3 months ago 24
Objective-C Question

Objective-C Singleton Class instance init function

I am learning to create a singleton class in Objective-C and came across this post which uses GCD to ensure singleton pattern is enforced. I am getting confused about the instance

init
method in this class and why it is there.

Looks like it will be invoked when someone tries to initialize
MyManager
instance but why is the author trying to initialize parent class's instance (
[super init]
) here?

#import "MyManager.h"

@implementation MyManager

@synthesize someProperty;

#pragma mark Singleton Methods

+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}

- (id)init {
//what is purpose of initialising parent class (NSObject's) instance
if (self = [super init]) {
someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
}
return self;
}

- (void)dealloc {
// Should never be called, but just here for clarity really.
}

@end

Answer

One subtle point of confusion with ObjC is that the language does not have static methods. It has class methods.

That is, the methods prefixed by + are attached to the Class object and are inherited and can be overridden just like instance methods.

Thus, when writing a singleton, the initialization of the singleton instance works just like every other instance initialization in that the superclass is given an opportunity to initialize, too.

Since most singletons inherit from NSObject, it is a no-op.

But, sometimes, you end up with:

NSObject
   AbstractSingletonThatIsNeverDirectlyInstantiated
      ConcreteSingletonForLocalOnlyMode
      ConcreteSingletonForOnlineMode

(Totally made up example, but I've seen similar.)