Working in C# and Java, I've seen basically one way everybody initializes singletons:
static obj _inst = null;
obj getInstance() {
if (_inst == null) {
_inst = new obj();
}
return _inst;
}
Now, when I move to Objective-C for the iPhone, whenever I see code samples, I see basically the same thing:
static obj _inst = nil;
+ (obj *) sharedObj {
if (!_inst) {
_inst = [[obj alloc] init];
}
return _inst;
}
There's a class method +initialize
that's called on every class in the Objective-C runtime before it's used. Is there any reason I couldn't use that to create my singletons?
static obj _inst = nil;
+ (void) initialize {
if (self == [obj class]) {
_inst = [[obj alloc] init];
}
}
+ (obj *) sharedObj {
return _inst;
}
It works just fine when I try it in my code, and it gets rid of checking to see if it exists every time before it's accessed. Is there any reason I shouldn't create singletons this way?