mercredi 6 janvier 2016

iOS: Singleton Class - accessing shared instance in class methods is good or bad practice?

What's the point of having a class method if we will access its own shared instance? The only reason of using it is the convenience of not writing sharedInstance every time. I would like to know others opinion.

+ (MyClass *)sharedInstance {
    static dispatch_once_t pred;
    __strong static MyClass *sharedInstance = nil;

    dispatch_once(&pred, ^{
        sharedInstance = [[MyClass alloc] init];
    });

    return sharedInstance;
}

+ (void)doSomething {
    // some code …
    [[MyClass sharedInstance] doSomethingElse];
}

- (void)doSomethingElse {
    // some code …
}

Aucun commentaire:

Enregistrer un commentaire