2

I was looking at modern patterns of Objective-C to create singletons after the introduction of instance

from: 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;
}

And I was wondering why not use [MyFunnyClass new] as below?

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

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

    return sharedInstance;
}

Or if it's the same?

(Ref: http://nshipster.com/instancetype/)

Edit: the answers given at Why use [ClassName alloc] instead of [[self class] alloc]? are not related to this question

Community
  • 1
  • 1
ppaulojr
  • 3,531
  • 4
  • 26
  • 55
  • possible duplicate of [Why use \[ClassName alloc\] instead of \[\[self class\] alloc\]?](http://stackoverflow.com/questions/3559763/why-use-classname-alloc-instead-of-self-class-alloc) – jlehr Sep 29 '15 at 19:58

2 Answers2

3

The reason, in this case, to use [self new] instead of [MyClass new], and to use static id sharedInstance instead of static MyClass *sharedInstance, is because you can just copy and paste the entire method without editing it. Nothing in the method is specific to the class it belongs to.

rob mayoff
  • 358,182
  • 62
  • 756
  • 811
0

See Why use [ClassName alloc] instead of [[self class] alloc]?

Also, the convention is to use alloc/init, not new. See alloc, init, and new in Objective-C

Community
  • 1
  • 1
raf
  • 2,459
  • 19
  • 19