我的 Objective-C 单例应该是什么样的? [英] What should my Objective-C singleton look like?
问题描述
我的单例访问器方法通常是以下的一些变体:
My singleton accessor method is usually some variant of:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
我可以做些什么来改善这一点?
What could I be doing to improve this?
推荐答案
另一种选择是使用 +(void)initialize
方法.来自文档:
Another option is to use the +(void)initialize
method. From the documentation:
运行时将 initialize
发送到程序中的每个类,恰好在该类或从它继承的任何类从程序内部发送其第一条消息之前.(因此,如果不使用该类,则该方法可能永远不会被调用.)运行时以线程安全的方式向类发送 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.
所以你可以做一些类似的事情:
So you could do something akin to this:
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}
这篇关于我的 Objective-C 单例应该是什么样的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!