objective-c - 我的 Objective-C 单例应该是什么样的?

就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the help center寻求指导。
关闭9年前

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

static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }

    return(gInstance);
}

我可以做些什么来改善这一点?

最佳答案

另一种选择是使用 +(void)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.

所以你可以做类似这样的事情:

static MySingleton *sharedSingleton;

+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        sharedSingleton = [[MySingleton alloc] init];
    }
}

https://stackoverflow.com/questions/145154/

相关文章:

ios - 如何在 iOS 7 上的 UINavigationController 中禁用向后滑动手

objective-c - 替换已弃用的 sizeWithFont : in iOS 7?

objective-c - 在不使用私有(private) API 的情况下获取当前的第一响应者

iphone - 找不到 -lPods 的库

objective-c - NSString 属性 : copy or retain?

objective-c - 对 Objective-C 代码进行单元测试的最佳方法是什么?

ios - 如何在 Swift 中发出 HTTP 请求?

ios - 将 NSURL 转换为 NSString

ios - dequeueReusableCellWithIdentifier :forIndexP

ios - 在 Xcode 6 中使用 AutoLayout 约束模拟方面适合行为