我的Objective-C单身人物应该怎么样? [英] What should my Objective-C singleton look like?

查看:127
本文介绍了我的Objective-C单身人物应该怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的单例访问器方法通常是以下变体:

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-C单身人物应该怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆