在Objective C中使用GCD的dispatch_once创建单例 [英] Create singleton using GCD's dispatch_once in Objective C

查看:76
本文介绍了在Objective C中使用GCD的dispatch_once创建单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您可以定位iOS 4.0或更高版本

If you can target iOS 4.0 or above

使用GCD,它是在Objective C(线程安全)中创建单例的最佳方式吗?

Using GCD, is it the best way to create singleton in Objective C (thread safe)?

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


推荐答案

这是完全可以接受的线程安全的方法来创建类的实例。从技术上讲,它可能不是单例(因为它们只能有1个这样的对象),但只要你只使用 [Foo sharedFoo] 方法访问该对象,这已经足够了。

This is a perfectly acceptable and thread-safe way to create an instance of your class. It may not technically be a "singleton" (in that there can only ever be 1 of these objects), but as long as you only use the [Foo sharedFoo] method to access the object, this is good enough.

这篇关于在Objective C中使用GCD的dispatch_once创建单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆