斗士狗 2008-09-28 03:38 采纳率: 0%
浏览 348
已采纳

我的 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?

转载于:https://stackoverflow.com/questions/145154/what-should-my-objective-c-singleton-look-like

  • 写回答

26条回答 默认 最新

  • 撒拉嘿哟木头 2008-12-05 08:24
    关注

    Another option is to use the +(void)initialize method. From the documentation:

    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];
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(25条)

报告相同问题?

悬赏问题

  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播