我的单例访问器方法通常是以下几种变体:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
我可以做些什么来改善这一点?
最佳答案
另一种选择是使用 +(void)initialize
方法。来自文档:
The runtime sends
initialize
to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends theinitialize
message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
所以你可以做类似这样的事情:
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}
https://stackoverflow.com/questions/145154/