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

查看:22
本文介绍了在 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天全站免登陆