问题描述
另一种选择是使用该+(void)initialize
方法。从文档中:
运行
initialize
时恰好在该类或从其继承的任何类从程序内部发送其第一条消息之前,一次将其发送到程序中的每个类。(因此,如果不使用该类,则可能永远不会调用该方法。)运行时initialize
以线程安全的方式将消息发送给类。超类在其子类之前收到此消息。
因此,您可以执行以下操作:
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}
解决方法
我的单例访问器方法通常是:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
我可以做些什么来改善这一点?