我的单例访问器方法通常是:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
我能做些什么来改善这一点?
我的单例访问器方法通常是:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
我能做些什么来改善这一点?
另一个 Select 是使用+(void)initialize
法.从文件中:
在类或从其继承的任何类从程序中发送第一条消息之前,运行库向程序中的每个类发送
initialize
次.(因此,如果不使用该类,可能永远不会调用该方法.)运行时以线程安全的方式向类发送initialize
条消息.超类在其子类之前收到此消息.
所以你可以做类似的事情:
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}