OGeek|极客世界-中国程序员成长平台

标题: ios - Objective-C 单例 GCD - [self alloc] 或 [Class alloc] [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 09:07
标题: ios - Objective-C 单例 GCD - [self alloc] 或 [Class alloc]

在引入 instance 后,我正在研究现代的 Objective-C 模式来创建单例

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

+ (instancetype)sharedInstance
{
    static dispatch_once_t once;
    static id sharedInstance;

    dispatch_once(&once, ^
    {
        sharedInstance = [self new];
    });

    return sharedInstance;
}

我想知道为什么不使用下面的 [MyFunnyClass new]?

@implementation MyFunnyClass
+ (instancetype)sharedInstance
{
    static dispatch_once_t once;
    static id sharedInstance;

    dispatch_once(&once, ^
    {
        sharedInstance = [MyFunnyClass new];
    });

    return sharedInstance;
}

或者如果它是一样的?

(引用:http://nshipster.com/instancetype/)

编辑:Why use [ClassName alloc] instead of [[self class] alloc]? 给出的答案与本题无关



Best Answer-推荐答案


在这种情况下,使用 [self new] 而不是 [MyClass new] 并使用 static id sharedInstance 的原因而不是 static MyClass *sharedInstance,是因为您可以复制和粘贴整个方法而无需对其进行编辑。该方法中没有任何内容特定于它所属的类。

关于ios - Objective-C 单例 GCD - [self alloc] 或 [Class alloc],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32851847/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4