问题
Does anyone have any preferences or comments about using either ...
static id sharedReactor = nil;
+(id)sharedInstance {
if(sharedReactor == nil) sharedReactor = [[super allocWithZone:NULL] init];
return sharedReactor;
}
OR:
static id sharedReactor = nil;
+(void)initialize {
if(sharedRandomReactor == nil) {
sharedRandomReactor = [[super allocWithZone:NULL] init];
}
+(id) sharedInstance {
return sharedReactor;
}
To my mind using +(void)initialize seems a lot more elegant, I am just curious what people with more experience than myself think of both approaches?
gary
回答1:
From Mike Ash's site here is another way using Grand Central Dispatch:
+ (id)sharedWhatever
{
static dispatch_once_t pred;
static Whatever *whatever = nil;
dispatch_once(&pred, ^{
whatever = [[Whatever alloc] init];
});
return whatever;
}
回答2:
I prefer +(id)instance
and a local static within the method itself. (more like the first example)
回答3:
The problem with the first option is that you now have one more responsibility which is calling the "Initialize" => more possible bugs.
However, the advantage of the second is that after you initialized the instance one, the code no longer checks if it's nil, so it's saves you few CPU cycles.
Even though, I'd go with the first one..
回答4:
This is the way to go...
static id sharedReactor = nil;
+(id)sharedInstance {
if(sharedReactor == nil) sharedReactor = [[super allocWithZone:NULL] init];
return sharedReactor;
}
Much clearer from both methods.
回答5:
I just spotted a blog entry from bbum regrading the possibility that +initialize can be executed more than once if a subClass does not implement it but the superClass does. As long as you keep this foible in mind +(void)initialize might well be the best option, particularity where you need thread safety and you don't want to take the hit of using @synchronized. After saying that if you just looking for simple singleton to use as a shared data model and are not to worried about thread safety then go with the first one.
回答6:
I've always followed the suggestions in the Cocoa Fundamentals guide from Apple. This way it doesn't matter if the class is instantiated multiple times, or accessed through a sharedInstance class method the object returned is always the same.
The guide also highlights the redefining the retain/release to prevent its resources from ever being reclaimed. Just FYI.
来源:https://stackoverflow.com/questions/2411507/singleton-where-to-create-instance