Ios Objective-C单例GCD-[自我分配]或[类别分配]

Ios Objective-C单例GCD-[自我分配]或[类别分配],ios,objective-c,singleton,Ios,Objective C,Singleton,在引入instance 发件人: 我想知道为什么不使用下面的[MyFunnyClass new] @implementation MyFunnyClass + (instancetype)sharedInstance { static dispatch_once_t once; static id sharedInstance; dispatch_once(&once, ^ { sharedInstance = [MyFunnyClass

在引入
instance

发件人:

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

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

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

    return sharedInstance;
}
或者如果是一样的

(参考号:)

编辑:在中给出的答案与此问题无关

请参见


此外,惯例是使用alloc/init,而不是新的。请参见

在这种情况下,使用
[self new]
而不是
[MyClass new]
,使用
静态id sharedInstance
而不是
静态MyClass*sharedInstance
的原因是,您只需复制并粘贴整个方法而无需编辑它。该方法中没有特定于它所属的类的内容。

的可能重复项
@implementation MyFunnyClass
+ (instancetype)sharedInstance
{
    static dispatch_once_t once;
    static id sharedInstance;

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

    return sharedInstance;
}