I would like to take the GCD approach of using shared instances to the next step so I created the following code:
@implementation MyClass
static id sharedInstance;
#pragma mark Initialization
+ (instancetype)sharedInstance {
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (instancetype)init {
if (sharedInstance) {
return sharedInstance;
}
@synchronized(self) {
self = [super init];
if (self) {
sharedInstance = self;
}
return self;
}
}
@end
I assume the sharedInstance
method seems to be ok but I am unsure about the init method. The reason for creating this is that I don't want people using my SDK, to use the init method, and if they do ... make it bullet proof.