【问题标题】:Create Singleton with ARC without using block使用 ARC 创建单例而不使用块
【发布时间】:2012-03-20 21:43:15
【问题描述】:

我想用 ARC 创建一个 Singleton,
this is the answer I see。

有没有在不使用块的情况下将此代码转换为类似的代码?

+ (MyClass *)sharedInstance
{
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

编辑:

我只看到这种方法:

static MyClass *sharedMyClassInstance = nil; 

+(MyClass *) sharedMyClass
{
    @synchronized(self) {
        if (sharedMyClassInstance == nil) {
            sharedMyClassInstance = [[self alloc] init];
        }
        return sharedMyClassInstance;
    }
}

这会阻止创建多个对象吗?

【问题讨论】:

    标签: singleton automatic-ref-counting objective-c-blocks


    【解决方案1】:

    是的,您可以使用其他同步机制,例如互斥锁。

    static MyClass *sharedInstance = nil;
    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    static volatile BOOL initialized = NO;
    
    pthread_mutex_lock(&mutex);
    
    if ( ! initialized ) {
        initialized = YES;
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    }
    
    pthread_mutex_unlock(&mutex);
    return sharedInstance;
    

    【讨论】:

    • 你能看看我的编辑,看看同步代码是否和你的一样。不过还是谢谢你的回答。
    【解决方案2】:

    有没有在不使用块的情况下将此代码转换为类似的代码?

    您可以继续分配您的共享对象,但您无法获得dispatch_once() 提供的保护。该功能可确保您为其提供的块在您的应用程序执行期间运行不超过一次。如果创建单例的代码在您传递给dispatch_once() 的块内,则您知道应用程序中的两个线程无法尝试同时访问共享对象,并可能导致它被创建两次。

    有什么原因你不想使用块吗?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2014-03-17
    相关资源
    最近更新 更多