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