我的单例访问器方法通常是以下的一些变体:
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 the initialize 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
发布评论