I was wondering where is the best place to initialize members of the singleton class.
I'm using Apple fundamental guide singleton implementation. Could you please pinpoint at what line the inits happen? The code is the following:
static MyGizmoClass *sharedGizmoManager = nil;
+ (MyGizmoClass*)sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
It's as with usual classes - add this above the block:
-(id)init {
if (self = [super init]) {
// do init here
}
return self;
}
It will be called when singleton is accessed first time.
You can initialise them in the init method, like any other class.
However, be mindful that if your singleton contains member state, it may no longer be threadsafe. Since a singleton is accessible anywhere in the app at any time, it may be accessed from different threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With