【问题标题】:Best singleton pattern for thread safe object [duplicate]线程安全对象的最佳单例模式
【发布时间】:2013-07-27 16:37:35
【问题描述】:

单例的最佳模式是什么?我经常使用

+ (SomeManager *)shared
{
    static SomeManager * _SomeManager = nil;
    if (_SomeManager) {
        return _SomeManager;
    }

    _SomeManager = [[SomeManager alloc] init];

    return _SomeManager;
}

这个线程安全吗?如果没有,要确保安全吗?

【问题讨论】:

  • NSLock or @synchronized or dispatch_once or etc...
  • 请记住,“单例”和“线程安全对象”是两个完全不同的东西。
  • 单例的延迟分配,通常代表少量的内存字节,是一种退化模式。在 +[SomeManger 初始化] 中分配你的单例,保证在类加载时只被调用一次。

标签: objective-c multithreading cocoa


【解决方案1】:

使用来自 Create singleton using GCD's dispatch_once in Objective C

+ (id)sharedInstance
{
    static dispatch_once_t once;
    static id sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

简洁明了。下次谷歌更好。

【讨论】:

    【解决方案2】:

    我更喜欢使用 GCD dispatch_once 方法...

    + (id) sharedSomethingManager
    {
        static dispatch_once_t onceQueue;
        static SomethingkManager *somethingManager = nil;
    
        dispatch_once(&onceQueue, ^{somethingManager = [[self alloc] init]; });
        return somethingManager;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      相关资源
      最近更新 更多