游.程 2008-09-28 03:38 采纳率: 0%
浏览 473
已采纳

我的 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条回答 默认 最新

  • lrony* 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条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题